From d0cdf8813ef099deec3b6940e34f20d1bba054b8 Mon Sep 17 00:00:00 2001 From: Ben Adams Date: Sun, 6 Jan 2019 02:49:58 +0100 Subject: (C#7) Use pattern matching `is` rather than `as` with null check (#21828) * Use pattern matching `is` rather than `as` with null check --- .../shared/System/AggregateException.cs | 4 +- .../shared/System/AppContext.cs | 3 +- .../shared/System/Collections/Comparer.cs | 9 +-- .../System/Collections/CompatibleComparer.cs | 3 +- .../Collections/Concurrent/ConcurrentQueue.cs | 6 +- .../System/Collections/ObjectModel/Collection.cs | 6 +- .../Collections/ObjectModel/ReadOnlyCollection.cs | 3 +- .../System/ComponentModel/DefaultValueAttribute.cs | 4 +- .../ComponentModel/EditorBrowsableAttribute.cs | 4 +- .../shared/System/Convert.cs | 18 ++---- .../System/Diagnostics/Tracing/EventSource.cs | 18 ++---- .../shared/System/Globalization/CompareInfo.cs | 4 +- .../shared/System/Globalization/CultureInfo.cs | 4 +- .../shared/System/Globalization/IdnMapping.cs | 3 +- .../shared/System/Globalization/RegionInfo.cs | 3 +- .../shared/System/Globalization/SortKey.cs | 4 +- .../shared/System/Globalization/StringInfo.cs | 3 +- .../shared/System/Globalization/TextInfo.cs | 4 +- .../System/IO/FileStreamCompletionSource.Win32.cs | 3 +- .../shared/System/IO/MemoryStream.cs | 3 +- .../shared/System/IO/Stream.cs | 6 +- .../shared/System/IO/TextWriter.cs | 6 +- .../shared/System/String.Comparison.cs | 7 +-- .../shared/System/StringComparer.cs | 24 +++----- .../shared/System/Text/DecoderBestFitFallback.cs | 3 +- .../shared/System/Text/DecoderExceptionFallback.cs | 3 +- .../System/Text/DecoderReplacementFallback.cs | 3 +- .../shared/System/Text/EncoderBestFitFallback.cs | 3 +- .../shared/System/Text/EncoderExceptionFallback.cs | 3 +- .../System/Text/EncoderReplacementFallback.cs | 3 +- .../shared/System/Text/Encoding.cs | 3 +- .../shared/System/Text/EncodingInfo.cs | 3 +- .../shared/System/Text/UTF32Encoding.cs | 3 +- .../shared/System/Text/UTF7Encoding.cs | 3 +- .../shared/System/Text/UTF8Encoding.cs | 3 +- .../shared/System/Text/UnicodeEncoding.cs | 3 +- .../shared/System/Threading/Tasks/Future.cs | 7 +-- .../System/Threading/Tasks/TaskExceptionHolder.cs | 15 ++--- .../shared/System/Threading/Tasks/TaskScheduler.cs | 3 +- .../shared/System/TimeZoneInfo.Win32.cs | 3 +- src/System.Private.CoreLib/shared/System/Tuple.cs | 64 ++++++---------------- src/System.Private.CoreLib/src/System/Array.cs | 10 +--- .../Collections/ObjectModel/ReadOnlyDictionary.cs | 24 +++----- .../Eventing/EventPipeMetadataGenerator.cs | 12 ++-- src/System.Private.CoreLib/src/System/Exception.cs | 3 +- .../src/System/MulticastDelegate.cs | 30 ++++------ .../System/Reflection/Emit/DynamicILGenerator.cs | 13 ++--- .../src/System/Resources/ResourceManager.cs | 6 +- src/System.Private.CoreLib/src/System/RtType.cs | 4 +- .../Runtime/CompilerServices/AsyncMethodBuilder.cs | 3 +- .../WindowsRuntime/CLRIPropertyValueImpl.cs | 9 +-- .../WindowsRuntime/CustomPropertyImpl.cs | 3 +- .../WindowsRuntime/DictionaryToMapAdapter.cs | 3 +- .../WindowsRuntime/ICustomPropertyProvider.cs | 19 +++---- .../IReadOnlyDictionaryToIMapViewAdapter.cs | 4 +- .../WindowsRuntime/ListToVectorAdapter.cs | 3 +- .../WindowsRuntime/MapToCollectionAdapter.cs | 15 ++--- .../MapViewToReadOnlyCollectionAdapter.cs | 3 +- .../InteropServices/WindowsRuntime/RuntimeClass.cs | 9 +-- .../src/System/Threading/Tasks/Task.cs | 47 ++++++---------- .../src/System/Threading/Tasks/TaskContinuation.cs | 28 ++++------ src/System.Private.CoreLib/src/System/Variant.cs | 3 +- 62 files changed, 173 insertions(+), 358 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/AggregateException.cs b/src/System.Private.CoreLib/shared/System/AggregateException.cs index 022a1eae39..048005c479 100644 --- a/src/System.Private.CoreLib/shared/System/AggregateException.cs +++ b/src/System.Private.CoreLib/shared/System/AggregateException.cs @@ -399,11 +399,9 @@ namespace System continue; } - AggregateException currentInnerAsAggregate = currentInnerException as AggregateException; - // If this exception is an aggregate, keep it around for later. Otherwise, // simply add it to the list of flattened exceptions to be returned. - if (currentInnerAsAggregate != null) + if (currentInnerException is AggregateException currentInnerAsAggregate) { exceptionsToFlatten.Add(currentInnerAsAggregate); } diff --git a/src/System.Private.CoreLib/shared/System/AppContext.cs b/src/System.Private.CoreLib/shared/System/AppContext.cs index 9df7c8dc8e..c3994ea351 100644 --- a/src/System.Private.CoreLib/shared/System/AppContext.cs +++ b/src/System.Private.CoreLib/shared/System/AppContext.cs @@ -99,8 +99,7 @@ namespace System } } - string value = GetData(switchName) as string; - if (value != null && bool.TryParse(value, out isEnabled)) + if (GetData(switchName) is string value && bool.TryParse(value, out isEnabled)) { return true; } diff --git a/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs b/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs index e22fb5bb91..24a6cbff62 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs @@ -59,16 +59,13 @@ namespace System.Collections if (b == null) return 1; string sa = a as string; - string sb = b as string; - if (sa != null && sb != null) + if (sa != null && b is string sb) return _compareInfo.Compare(sa, sb); - IComparable ia = a as IComparable; - if (ia != null) + if (a is IComparable ia) return ia.CompareTo(b); - IComparable ib = b as IComparable; - if (ib != null) + if (b is IComparable ib) return -ib.CompareTo(a); throw new ArgumentException(SR.Argument_ImplementIComparable); diff --git a/src/System.Private.CoreLib/shared/System/Collections/CompatibleComparer.cs b/src/System.Private.CoreLib/shared/System/Collections/CompatibleComparer.cs index 587fd68391..5342dcd6fb 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/CompatibleComparer.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/CompatibleComparer.cs @@ -37,8 +37,7 @@ namespace System.Collections return _comparer.Compare(a, b); } - IComparable ia = a as IComparable; - if (ia != null) + if (a is IComparable ia) { return ia.CompareTo(b); } diff --git a/src/System.Private.CoreLib/shared/System/Collections/Concurrent/ConcurrentQueue.cs b/src/System.Private.CoreLib/shared/System/Collections/Concurrent/ConcurrentQueue.cs index f3634e8864..17e7fd5b77 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/Concurrent/ConcurrentQueue.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/Concurrent/ConcurrentQueue.cs @@ -80,8 +80,7 @@ namespace System.Collections.Concurrent // case we round its length up to a power of 2, as all segments must // be a power of 2 in length. int length = InitialSegmentLength; - var c = collection as ICollection; - if (c != null) + if (collection is ICollection c) { int count = c.Count; if (count > length) @@ -143,8 +142,7 @@ namespace System.Collections.Concurrent void ICollection.CopyTo(Array array, int index) { // Special-case when the Array is actually a T[], taking a faster path - T[] szArray = array as T[]; - if (szArray != null) + if (array is T[] szArray) { CopyTo(szArray, index); return; diff --git a/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/Collection.cs b/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/Collection.cs index 9efd671275..c96a1576f3 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/Collection.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/Collection.cs @@ -215,8 +215,7 @@ namespace System.Collections.ObjectModel ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } - T[] tArray = array as T[]; - if (tArray != null) + if (array is T[] tArray) { items.CopyTo(tArray, index); } @@ -294,8 +293,7 @@ namespace System.Collections.ObjectModel // readonly collections are fixed size, if our internal item // collection does not implement IList. Note that Array implements // IList, and therefore T[] and U[] will be fixed-size. - IList list = items as IList; - if (list != null) + if (items is IList list) { return list.IsFixedSize; } diff --git a/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs b/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs index 584b4cc711..9d463da751 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs @@ -147,8 +147,7 @@ namespace System.Collections.ObjectModel ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } - T[] items = array as T[]; - if (items != null) + if (array is T[] items) { list.CopyTo(items, index); } diff --git a/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs b/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs index 5f7108a527..d506ffae4c 100644 --- a/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs @@ -225,9 +225,7 @@ namespace System.ComponentModel return true; } - DefaultValueAttribute other = obj as DefaultValueAttribute; - - if (other != null) + if (obj is DefaultValueAttribute other) { if (Value != null) { diff --git a/src/System.Private.CoreLib/shared/System/ComponentModel/EditorBrowsableAttribute.cs b/src/System.Private.CoreLib/shared/System/ComponentModel/EditorBrowsableAttribute.cs index 9b4d6e626e..a59ee839bc 100644 --- a/src/System.Private.CoreLib/shared/System/ComponentModel/EditorBrowsableAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/ComponentModel/EditorBrowsableAttribute.cs @@ -28,9 +28,7 @@ namespace System.ComponentModel return true; } - EditorBrowsableAttribute other = obj as EditorBrowsableAttribute; - - return (other != null) && other.browsableState == browsableState; + return (obj is EditorBrowsableAttribute other) && other.browsableState == browsableState; } public override int GetHashCode() diff --git a/src/System.Private.CoreLib/shared/System/Convert.cs b/src/System.Private.CoreLib/shared/System/Convert.cs index 077dda9d4f..2bc01794e4 100644 --- a/src/System.Private.CoreLib/shared/System/Convert.cs +++ b/src/System.Private.CoreLib/shared/System/Convert.cs @@ -160,8 +160,7 @@ namespace System public static TypeCode GetTypeCode(object value) { if (value == null) return TypeCode.Empty; - IConvertible temp = value as IConvertible; - if (temp != null) + if (value is IConvertible temp) { return temp.GetTypeCode(); } @@ -173,8 +172,7 @@ namespace System public static bool IsDBNull(object value) { if (value == System.DBNull.Value) return true; - IConvertible convertible = value as IConvertible; - return convertible != null ? convertible.GetTypeCode() == TypeCode.DBNull : false; + return value is IConvertible convertible ? convertible.GetTypeCode() == TypeCode.DBNull : false; } // Converts the given object to the given type. In general, this method is @@ -201,8 +199,7 @@ namespace System return null; } - IConvertible v = value as IConvertible; - if (v == null) + if (!(value is IConvertible v)) { throw new InvalidCastException(SR.InvalidCast_IConvertible); } @@ -330,8 +327,7 @@ namespace System return null; } - IConvertible ic = value as IConvertible; - if (ic == null) + if (!(value is IConvertible ic)) { if (value.GetType() == conversionType) { @@ -2002,11 +1998,9 @@ namespace System public static string ToString(object value, IFormatProvider provider) { - IConvertible ic = value as IConvertible; - if (ic != null) + if (value is IConvertible ic) return ic.ToString(provider); - IFormattable formattable = value as IFormattable; - if (formattable != null) + if (value is IFormattable formattable) return formattable.ToString(null, provider); return value == null ? string.Empty : value.ToString(); } diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs index 3dc1cb050b..8159bad6b2 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs @@ -403,8 +403,7 @@ namespace System.Diagnostics.Tracing { foreach (WeakReference eventSourceRef in EventListener.s_EventSources) { - EventSource eventSource = eventSourceRef.Target as EventSource; - if (eventSource != null && !eventSource.IsDisposed) + if (eventSourceRef.Target is EventSource eventSource && !eventSource.IsDisposed) ret.Add(eventSource); } } @@ -2715,8 +2714,7 @@ namespace System.Diagnostics.Tracing // TODO Enforce singleton pattern foreach (WeakReference eventSourceRef in EventListener.s_EventSources) { - EventSource eventSource = eventSourceRef.Target as EventSource; - if (eventSource != null && eventSource.Guid == m_guid && !eventSource.IsDisposed) + if (eventSourceRef.Target is EventSource eventSource && eventSource.Guid == m_guid && !eventSource.IsDisposed) { if (eventSource != this) { @@ -4160,8 +4158,7 @@ namespace System.Diagnostics.Tracing { foreach (var esRef in s_EventSources) { - EventSource es = esRef.Target as EventSource; - if (es != null) + if (esRef.Target is EventSource es) es.Dispose(); } } @@ -4181,8 +4178,7 @@ namespace System.Diagnostics.Tracing // Foreach existing EventSource in the appdomain foreach (WeakReference eventSourceRef in s_EventSources) { - EventSource eventSource = eventSourceRef.Target as EventSource; - if (eventSource != null) + if (eventSourceRef.Target is EventSource eventSource) { // Is the first output dispatcher the dispatcher we are removing? if (eventSource.m_Dispatchers.m_Listener == listenerToRemove) @@ -4246,8 +4242,7 @@ namespace System.Diagnostics.Tracing foreach (WeakReference eventSourceRef in s_EventSources) { id++; - EventSource eventSource = eventSourceRef.Target as EventSource; - if (eventSource == null) + if (!(eventSourceRef.Target is EventSource eventSource)) continue; Debug.Assert(eventSource.m_id == id, "Unexpected event source ID."); @@ -4328,8 +4323,7 @@ namespace System.Diagnostics.Tracing for (int i = 0; i < eventSourcesSnapshot.Length; i++) { WeakReference eventSourceRef = eventSourcesSnapshot[i]; - EventSource eventSource = eventSourceRef.Target as EventSource; - if (eventSource != null) + if (eventSourceRef.Target is EventSource eventSource) { EventSourceCreatedEventArgs args = new EventSourceCreatedEventArgs(); args.EventSource = eventSource; diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.cs index 21fd7212a8..9f7669edcc 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.cs @@ -1371,9 +1371,7 @@ namespace System.Globalization public override bool Equals(object value) { - CompareInfo that = value as CompareInfo; - - if (that != null) + if (value is CompareInfo that) { return this.Name == that.Name; } diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CultureInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/CultureInfo.cs index f3f56dda3e..153512639a 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CultureInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CultureInfo.cs @@ -872,9 +872,7 @@ namespace System.Globalization if (object.ReferenceEquals(this, value)) return true; - CultureInfo that = value as CultureInfo; - - if (that != null) + if (value is CultureInfo that) { // using CompareInfo to verify the data passed through the constructor // CultureInfo(String cultureName, String textAndCompareCultureName) diff --git a/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.cs b/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.cs index 849602abcb..56f38ff628 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.cs @@ -145,9 +145,8 @@ namespace System.Globalization public override bool Equals(object obj) { - IdnMapping that = obj as IdnMapping; return - that != null && + obj is IdnMapping that && _allowUnassigned == that._allowUnassigned && _useStd3AsciiRules == that._useStd3AsciiRules; } diff --git a/src/System.Private.CoreLib/shared/System/Globalization/RegionInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/RegionInfo.cs index 8416257d91..576672b222 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/RegionInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/RegionInfo.cs @@ -360,8 +360,7 @@ namespace System.Globalization //////////////////////////////////////////////////////////////////////// public override bool Equals(object value) { - RegionInfo that = value as RegionInfo; - if (that != null) + if (value is RegionInfo that) { return this.Name.Equals(that.Name); } diff --git a/src/System.Private.CoreLib/shared/System/Globalization/SortKey.cs b/src/System.Private.CoreLib/shared/System/Globalization/SortKey.cs index 9624946257..f9c7f68f5e 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/SortKey.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/SortKey.cs @@ -135,9 +135,7 @@ namespace System.Globalization //////////////////////////////////////////////////////////////////////// public override bool Equals(object value) { - SortKey that = value as SortKey; - - if (that != null) + if (value is SortKey that) { return Compare(this, that) == 0; } diff --git a/src/System.Private.CoreLib/shared/System/Globalization/StringInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/StringInfo.cs index 936a3cb9c1..425e6f2379 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/StringInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/StringInfo.cs @@ -34,8 +34,7 @@ namespace System.Globalization public override bool Equals(object value) { - StringInfo that = value as StringInfo; - if (that != null) + if (value is StringInfo that) { return (_str.Equals(that._str)); } diff --git a/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs index 61e2160a62..77964fb642 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs @@ -654,9 +654,7 @@ namespace System.Globalization //////////////////////////////////////////////////////////////////////// public override bool Equals(object obj) { - TextInfo that = obj as TextInfo; - - if (that != null) + if (obj is TextInfo that) { return CultureName.Equals(that.CultureName); } diff --git a/src/System.Private.CoreLib/shared/System/IO/FileStreamCompletionSource.Win32.cs b/src/System.Private.CoreLib/shared/System/IO/FileStreamCompletionSource.Win32.cs index ec499d8456..a7996fd042 100644 --- a/src/System.Private.CoreLib/shared/System/IO/FileStreamCompletionSource.Win32.cs +++ b/src/System.Private.CoreLib/shared/System/IO/FileStreamCompletionSource.Win32.cs @@ -137,8 +137,7 @@ namespace System.IO // be directly the FileStreamCompletion that's completing (in the case where the preallocated // overlapped was already in use by another operation). object state = ThreadPoolBoundHandle.GetNativeOverlappedState(pOverlapped); - FileStream fs = state as FileStream; - FileStreamCompletionSource completionSource = fs != null ? + FileStreamCompletionSource completionSource = state is FileStream fs ? fs._currentOverlappedOwner : (FileStreamCompletionSource)state; Debug.Assert(completionSource._overlapped == pOverlapped, "Overlaps don't match"); diff --git a/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs b/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs index 8ca162b57c..b9f2b5e35f 100644 --- a/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs +++ b/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs @@ -527,8 +527,7 @@ namespace System.IO return Task.CompletedTask; // If destination is not a memory stream, write there asynchronously: - MemoryStream memStrDest = destination as MemoryStream; - if (memStrDest == null) + if (!(destination is MemoryStream memStrDest)) return destination.WriteAsync(_buffer, pos, n, cancellationToken); try diff --git a/src/System.Private.CoreLib/shared/System/IO/Stream.cs b/src/System.Private.CoreLib/shared/System/IO/Stream.cs index fe9f9fe24e..537d28ca8a 100644 --- a/src/System.Private.CoreLib/shared/System/IO/Stream.cs +++ b/src/System.Private.CoreLib/shared/System/IO/Stream.cs @@ -1078,8 +1078,7 @@ namespace System.IO internal static int EndRead(IAsyncResult asyncResult) { - SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult; - if (ar == null || ar._isWrite) + if (!(asyncResult is SynchronousAsyncResult ar) || ar._isWrite) throw new ArgumentException(SR.Arg_WrongAsyncResult); if (ar._endXxxCalled) @@ -1093,8 +1092,7 @@ namespace System.IO internal static void EndWrite(IAsyncResult asyncResult) { - SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult; - if (ar == null || !ar._isWrite) + if (!(asyncResult is SynchronousAsyncResult ar) || !ar._isWrite) throw new ArgumentException(SR.Arg_WrongAsyncResult); if (ar._endXxxCalled) diff --git a/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs b/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs index e470517a7b..030a015e3c 100644 --- a/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs +++ b/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs @@ -286,8 +286,7 @@ namespace System.IO { if (value != null) { - IFormattable f = value as IFormattable; - if (f != null) + if (value is IFormattable f) { Write(f.ToString(null, FormatProvider)); } @@ -497,8 +496,7 @@ namespace System.IO { // Call WriteLine(value.ToString), not Write(Object), WriteLine(). // This makes calls to WriteLine(Object) atomic. - IFormattable f = value as IFormattable; - if (f != null) + if (value is IFormattable f) { WriteLine(f.ToString(null, FormatProvider)); } diff --git a/src/System.Private.CoreLib/shared/System/String.Comparison.cs b/src/System.Private.CoreLib/shared/System/String.Comparison.cs index 360167df40..5bae67be0e 100644 --- a/src/System.Private.CoreLib/shared/System/String.Comparison.cs +++ b/src/System.Private.CoreLib/shared/System/String.Comparison.cs @@ -511,9 +511,7 @@ namespace System return 1; } - string other = value as string; - - if (other == null) + if (!(value is string other)) { throw new ArgumentException(SR.Arg_MustBeString); } @@ -606,8 +604,7 @@ namespace System if (object.ReferenceEquals(this, obj)) return true; - string str = obj as string; - if (str == null) + if (!(obj is string str)) return false; if (this.Length != str.Length) diff --git a/src/System.Private.CoreLib/shared/System/StringComparer.cs b/src/System.Private.CoreLib/shared/System/StringComparer.cs index e4378c5efa..8fab833592 100644 --- a/src/System.Private.CoreLib/shared/System/StringComparer.cs +++ b/src/System.Private.CoreLib/shared/System/StringComparer.cs @@ -114,18 +114,15 @@ namespace System if (x == null) return -1; if (y == null) return 1; - string sa = x as string; - if (sa != null) + if (x is string sa) { - string sb = y as string; - if (sb != null) + if (y is string sb) { return Compare(sa, sb); } } - IComparable ia = x as IComparable; - if (ia != null) + if (x is IComparable ia) { return ia.CompareTo(y); } @@ -138,11 +135,9 @@ namespace System if (x == y) return true; if (x == null || y == null) return false; - string sa = x as string; - if (sa != null) + if (x is string sa) { - string sb = y as string; - if (sb != null) + if (y is string sb) { return Equals(sa, sb); } @@ -157,8 +152,7 @@ namespace System throw new ArgumentNullException(nameof(obj)); } - string s = obj as string; - if (s != null) + if (obj is string s) { return GetHashCode(s); } @@ -232,9 +226,8 @@ namespace System // Equals method for the comparer itself. public override bool Equals(object obj) { - CultureAwareComparer comparer = obj as CultureAwareComparer; return - comparer != null && + obj is CultureAwareComparer comparer && _options == comparer._options && _compareInfo.Equals(comparer._compareInfo); } @@ -316,8 +309,7 @@ namespace System // Equals method for the comparer itself. public override bool Equals(object obj) { - OrdinalComparer comparer = obj as OrdinalComparer; - if (comparer == null) + if (!(obj is OrdinalComparer comparer)) { return false; } diff --git a/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs b/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs index 8c62730c26..d94554c6fd 100644 --- a/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs @@ -40,8 +40,7 @@ namespace System.Text public override bool Equals(object value) { - InternalDecoderBestFitFallback that = value as InternalDecoderBestFitFallback; - if (that != null) + if (value is InternalDecoderBestFitFallback that) { return (_encoding.CodePage == that._encoding.CodePage); } diff --git a/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs b/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs index 56c004714f..0525861a5b 100644 --- a/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs @@ -31,8 +31,7 @@ namespace System.Text public override bool Equals(object value) { - DecoderExceptionFallback that = value as DecoderExceptionFallback; - if (that != null) + if (value is DecoderExceptionFallback that) { return (true); } diff --git a/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs b/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs index a97baf05cb..2af0d12535 100644 --- a/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs @@ -84,8 +84,7 @@ namespace System.Text public override bool Equals(object value) { - DecoderReplacementFallback that = value as DecoderReplacementFallback; - if (that != null) + if (value is DecoderReplacementFallback that) { return (_strDefault == that._strDefault); } diff --git a/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs b/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs index 4aab3f62a3..c3d07c980e 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs @@ -40,8 +40,7 @@ namespace System.Text public override bool Equals(object value) { - InternalEncoderBestFitFallback that = value as InternalEncoderBestFitFallback; - if (that != null) + if (value is InternalEncoderBestFitFallback that) { return (_encoding.CodePage == that._encoding.CodePage); } diff --git a/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs b/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs index 92afcf701a..077d92762f 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs @@ -30,8 +30,7 @@ namespace System.Text public override bool Equals(object value) { - EncoderExceptionFallback that = value as EncoderExceptionFallback; - if (that != null) + if (value is EncoderExceptionFallback that) { return (true); } diff --git a/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs b/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs index 760c280fde..cfce4108f5 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs @@ -87,8 +87,7 @@ namespace System.Text public override bool Equals(object value) { - EncoderReplacementFallback that = value as EncoderReplacementFallback; - if (that != null) + if (value is EncoderReplacementFallback that) { return (_strDefault == that._strDefault); } diff --git a/src/System.Private.CoreLib/shared/System/Text/Encoding.cs b/src/System.Private.CoreLib/shared/System/Text/Encoding.cs index c1b64961f7..175e5442fd 100644 --- a/src/System.Private.CoreLib/shared/System/Text/Encoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/Encoding.cs @@ -1190,8 +1190,7 @@ namespace System.Text public override bool Equals(object value) { - Encoding that = value as Encoding; - if (that != null) + if (value is Encoding that) return (_codePage == that._codePage) && (EncoderFallback.Equals(that.EncoderFallback)) && (DecoderFallback.Equals(that.DecoderFallback)); diff --git a/src/System.Private.CoreLib/shared/System/Text/EncodingInfo.cs b/src/System.Private.CoreLib/shared/System/Text/EncodingInfo.cs index b8d634c22e..002d9ef0b5 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncodingInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncodingInfo.cs @@ -24,8 +24,7 @@ namespace System.Text public override bool Equals(object value) { - EncodingInfo that = value as EncodingInfo; - if (that != null) + if (value is EncodingInfo that) { return this.CodePage == that.CodePage; } diff --git a/src/System.Private.CoreLib/shared/System/Text/UTF32Encoding.cs b/src/System.Private.CoreLib/shared/System/Text/UTF32Encoding.cs index d579cc9e5e..02f3167df2 100644 --- a/src/System.Private.CoreLib/shared/System/Text/UTF32Encoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/UTF32Encoding.cs @@ -1159,8 +1159,7 @@ namespace System.Text public override bool Equals(object value) { - UTF32Encoding that = value as UTF32Encoding; - if (that != null) + if (value is UTF32Encoding that) { return (_emitUTF32ByteOrderMark == that._emitUTF32ByteOrderMark) && (_bigEndian == that._bigEndian) && diff --git a/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs b/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs index 5c51c81076..a932778b45 100644 --- a/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs @@ -99,8 +99,7 @@ namespace System.Text public override bool Equals(object value) { - UTF7Encoding that = value as UTF7Encoding; - if (that != null) + if (value is UTF7Encoding that) { return (_allowOptionals == that._allowOptionals) && (EncoderFallback.Equals(that.EncoderFallback)) && diff --git a/src/System.Private.CoreLib/shared/System/Text/UTF8Encoding.cs b/src/System.Private.CoreLib/shared/System/Text/UTF8Encoding.cs index 426835ed53..5e1b9ae9a3 100644 --- a/src/System.Private.CoreLib/shared/System/Text/UTF8Encoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/UTF8Encoding.cs @@ -2555,8 +2555,7 @@ namespace System.Text public override bool Equals(object value) { - UTF8Encoding that = value as UTF8Encoding; - if (that != null) + if (value is UTF8Encoding that) { return (_emitUTF8Identifier == that._emitUTF8Identifier) && (EncoderFallback.Equals(that.EncoderFallback)) && diff --git a/src/System.Private.CoreLib/shared/System/Text/UnicodeEncoding.cs b/src/System.Private.CoreLib/shared/System/Text/UnicodeEncoding.cs index d80c229693..870962c6b6 100644 --- a/src/System.Private.CoreLib/shared/System/Text/UnicodeEncoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/UnicodeEncoding.cs @@ -1842,8 +1842,7 @@ namespace System.Text public override bool Equals(object value) { - UnicodeEncoding that = value as UnicodeEncoding; - if (that != null) + if (value is UnicodeEncoding that) { // // Big Endian Unicode has different code page (1201) than small Endian one (1200), diff --git a/src/System.Private.CoreLib/shared/System/Threading/Tasks/Future.cs b/src/System.Private.CoreLib/shared/System/Threading/Tasks/Future.cs index e3339efd42..5cc0b6737b 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/Tasks/Future.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/Tasks/Future.cs @@ -597,14 +597,13 @@ namespace System.Threading.Tasks { // Invoke the delegate Debug.Assert(m_action != null); - var func = m_action as Func; - if (func != null) + if (m_action is Func func) { m_result = func(); return; } - var funcWithState = m_action as Func; - if (funcWithState != null) + + if (m_action is Func funcWithState) { m_result = funcWithState(m_stateObject); return; diff --git a/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskExceptionHolder.cs b/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskExceptionHolder.cs index 0037923bdb..cdf5c78ea4 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskExceptionHolder.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskExceptionHolder.cs @@ -123,8 +123,7 @@ namespace System.Threading.Tasks // If this changes, make sure to only conditionally mark as handled below. // Store the cancellation exception - var oce = exceptionObject as OperationCanceledException; - if (oce != null) + if (exceptionObject is OperationCanceledException oce) { m_cancellationException = ExceptionDispatchInfo.Capture(oce); } @@ -155,24 +154,21 @@ namespace System.Threading.Tasks 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 - var exception = exceptionObject as Exception; - if (exception != null) + if (exceptionObject is Exception exception) { exceptions.Add(ExceptionDispatchInfo.Capture(exception)); } else { // Handle ExceptionDispatchInfo by storing it into the list - var edi = exceptionObject as ExceptionDispatchInfo; - if (edi != null) + if (exceptionObject is ExceptionDispatchInfo edi) { exceptions.Add(edi); } else { // Handle enumerables of exceptions by capturing each of the contained exceptions into an EDI and storing it - var exColl = exceptionObject as IEnumerable; - if (exColl != null) + if (exceptionObject is IEnumerable exColl) { #if DEBUG int numExceptions = 0; @@ -192,8 +188,7 @@ namespace System.Threading.Tasks else { // Handle enumerables of EDIs by storing them directly - var ediColl = exceptionObject as IEnumerable; - if (ediColl != null) + if (exceptionObject is IEnumerable ediColl) { exceptions.AddRange(ediColl); #if DEBUG diff --git a/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskScheduler.cs b/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskScheduler.cs index c5bf02b9bc..13257b3077 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskScheduler.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskScheduler.cs @@ -500,8 +500,7 @@ namespace System.Threading.Tasks return null; // If it can be cast to an array, use it directly - Task[] activeTasksArray = activeTasksSource as Task[]; - if (activeTasksArray == null) + if (!(activeTasksSource is Task[] activeTasksArray)) { activeTasksArray = (new List(activeTasksSource)).ToArray(); } diff --git a/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Win32.cs b/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Win32.cs index a16f6a8764..a7095dee61 100644 --- a/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Win32.cs +++ b/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Win32.cs @@ -678,8 +678,7 @@ namespace System private static unsafe bool TryGetTimeZoneEntryFromRegistry(RegistryKey key, string name, out REG_TZI_FORMAT dtzi) { - byte[] regValue = key.GetValue(name, null) as byte[]; - if (regValue == null || regValue.Length != sizeof(REG_TZI_FORMAT)) + if (!(key.GetValue(name, null) is byte[] regValue) || regValue.Length != sizeof(REG_TZI_FORMAT)) { dtzi = default; return false; diff --git a/src/System.Private.CoreLib/shared/System/Tuple.cs b/src/System.Private.CoreLib/shared/System/Tuple.cs index ebbd156dda..bb72e4f0ec 100644 --- a/src/System.Private.CoreLib/shared/System/Tuple.cs +++ b/src/System.Private.CoreLib/shared/System/Tuple.cs @@ -124,9 +124,7 @@ namespace System { if (other == null) return false; - Tuple objTuple = other as Tuple; - - if (objTuple == null) + if (!(other is Tuple objTuple)) { return false; } @@ -143,9 +141,7 @@ namespace System { if (other == null) return 1; - Tuple objTuple = other as Tuple; - - if (objTuple == null) + if (!(other is Tuple objTuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), nameof(other)); } @@ -227,9 +223,7 @@ namespace System { if (other == null) return false; - Tuple objTuple = other as Tuple; - - if (objTuple == null) + if (!(other is Tuple objTuple)) { return false; } @@ -246,9 +240,7 @@ namespace System { if (other == null) return 1; - Tuple objTuple = other as Tuple; - - if (objTuple == null) + if (!(other is Tuple objTuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), nameof(other)); } @@ -345,9 +337,7 @@ namespace System { if (other == null) return false; - Tuple objTuple = other as Tuple; - - if (objTuple == null) + if (!(other is Tuple objTuple)) { return false; } @@ -364,9 +354,7 @@ namespace System { if (other == null) return 1; - Tuple objTuple = other as Tuple; - - if (objTuple == null) + if (!(other is Tuple objTuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), nameof(other)); } @@ -474,9 +462,7 @@ namespace System { if (other == null) return false; - Tuple objTuple = other as Tuple; - - if (objTuple == null) + if (!(other is Tuple objTuple)) { return false; } @@ -493,9 +479,7 @@ namespace System { if (other == null) return 1; - Tuple objTuple = other as Tuple; - - if (objTuple == null) + if (!(other is Tuple objTuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), nameof(other)); } @@ -614,9 +598,7 @@ namespace System { if (other == null) return false; - Tuple objTuple = other as Tuple; - - if (objTuple == null) + if (!(other is Tuple objTuple)) { return false; } @@ -633,9 +615,7 @@ namespace System { if (other == null) return 1; - Tuple objTuple = other as Tuple; - - if (objTuple == null) + if (!(other is Tuple objTuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), nameof(other)); } @@ -765,9 +745,7 @@ namespace System { if (other == null) return false; - Tuple objTuple = other as Tuple; - - if (objTuple == null) + if (!(other is Tuple objTuple)) { return false; } @@ -784,9 +762,7 @@ namespace System { if (other == null) return 1; - Tuple objTuple = other as Tuple; - - if (objTuple == null) + if (!(other is Tuple objTuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), nameof(other)); } @@ -927,9 +903,7 @@ namespace System { if (other == null) return false; - Tuple objTuple = other as Tuple; - - if (objTuple == null) + if (!(other is Tuple objTuple)) { return false; } @@ -946,9 +920,7 @@ namespace System { if (other == null) return 1; - Tuple objTuple = other as Tuple; - - if (objTuple == null) + if (!(other is Tuple objTuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), nameof(other)); } @@ -1105,9 +1077,7 @@ namespace System { if (other == null) return false; - Tuple objTuple = other as Tuple; - - if (objTuple == null) + if (!(other is Tuple objTuple)) { return false; } @@ -1124,9 +1094,7 @@ namespace System { if (other == null) return 1; - Tuple objTuple = other as Tuple; - - if (objTuple == null) + if (!(other is Tuple objTuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), nameof(other)); } diff --git a/src/System.Private.CoreLib/src/System/Array.cs b/src/System.Private.CoreLib/src/System/Array.cs index 490ef91075..41e8d794f5 100644 --- a/src/System.Private.CoreLib/src/System/Array.cs +++ b/src/System.Private.CoreLib/src/System/Array.cs @@ -674,9 +674,7 @@ namespace System return true; } - Array o = other as Array; - - if (o == null || o.Length != this.Length) + if (!(other is Array o) || o.Length != this.Length) { return false; } @@ -819,8 +817,7 @@ namespace System int lo = index; int hi = index + length - 1; - object[] objArray = array as object[]; - if (objArray != null) + if (array is object[] objArray) { while (lo <= hi) { @@ -1599,8 +1596,7 @@ namespace System if (r) return; - object[] objArray = array as object[]; - if (objArray != null) + if (array is object[] objArray) { Array.Reverse(objArray, index, length); } diff --git a/src/System.Private.CoreLib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs b/src/System.Private.CoreLib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs index 29446b29c5..998fa64875 100644 --- a/src/System.Private.CoreLib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs +++ b/src/System.Private.CoreLib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs @@ -212,8 +212,7 @@ namespace System.Collections.ObjectModel IDictionaryEnumerator IDictionary.GetEnumerator() { - IDictionary d = m_dictionary as IDictionary; - if (d != null) + if (m_dictionary is IDictionary d) { return d.GetEnumerator(); } @@ -294,15 +293,13 @@ namespace System.Collections.ObjectModel ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } - KeyValuePair[] pairs = array as KeyValuePair[]; - if (pairs != null) + if (array is KeyValuePair[] pairs) { m_dictionary.CopyTo(pairs, index); } else { - DictionaryEntry[] dictEntryArray = array as DictionaryEntry[]; - if (dictEntryArray != null) + if (array is DictionaryEntry[] dictEntryArray) { foreach (var item in m_dictionary) { @@ -343,8 +340,7 @@ namespace System.Collections.ObjectModel { if (m_syncRoot == null) { - ICollection c = m_dictionary as ICollection; - if (c != null) + if (m_dictionary is ICollection c) { m_syncRoot = c.SyncRoot; } @@ -513,8 +509,7 @@ namespace System.Collections.ObjectModel { if (m_syncRoot == null) { - ICollection c = m_collection as ICollection; - if (c != null) + if (m_collection is ICollection c) { m_syncRoot = c.SyncRoot; } @@ -622,8 +617,7 @@ namespace System.Collections.ObjectModel { if (m_syncRoot == null) { - ICollection c = m_collection as ICollection; - if (c != null) + if (m_collection is ICollection c) { m_syncRoot = c.SyncRoot; } @@ -674,15 +668,13 @@ namespace System.Collections.ObjectModel } // Easy out if the ICollection implements the non-generic ICollection - ICollection nonGenericCollection = collection as ICollection; - if (nonGenericCollection != null) + if (collection is ICollection nonGenericCollection) { nonGenericCollection.CopyTo(array, index); return; } - T[] items = array as T[]; - if (items != null) + if (array is T[] items) { collection.CopyTo(items, index); } diff --git a/src/System.Private.CoreLib/src/System/Diagnostics/Eventing/EventPipeMetadataGenerator.cs b/src/System.Private.CoreLib/src/System/Diagnostics/Eventing/EventPipeMetadataGenerator.cs index 06aa854207..991b818989 100644 --- a/src/System.Private.CoreLib/src/System/Diagnostics/Eventing/EventPipeMetadataGenerator.cs +++ b/src/System.Private.CoreLib/src/System/Diagnostics/Eventing/EventPipeMetadataGenerator.cs @@ -186,8 +186,7 @@ namespace System.Diagnostics.Tracing // Nested struct property name : NULL-terminated string. EventPipeMetadataGenerator.WriteToBuffer(pMetadataBlob, blobSize, ref offset, (uint)TypeCode.Object); - InvokeTypeInfo invokeTypeInfo = TypeInfo as InvokeTypeInfo; - if(invokeTypeInfo == null) + if(!(TypeInfo is InvokeTypeInfo invokeTypeInfo)) { throw new NotSupportedException(); } @@ -233,8 +232,7 @@ namespace System.Diagnostics.Tracing Debug.Assert(pMetadataBlob != null); // Check if this property is a nested struct. - InvokeTypeInfo invokeTypeInfo = property.typeInfo as InvokeTypeInfo; - if(invokeTypeInfo != null) + if(property.typeInfo is InvokeTypeInfo invokeTypeInfo) { // Each nested struct is serialized as: // TypeCode.Object : 4 bytes @@ -299,8 +297,7 @@ namespace System.Diagnostics.Tracing TypeCode typeCode = GetTypeCodeExtended(ParameterType); if(typeCode == TypeCode.Object) { - InvokeTypeInfo typeInfo = TypeInfo as InvokeTypeInfo; - if(typeInfo == null) + if(!(TypeInfo is InvokeTypeInfo typeInfo)) { throw new NotSupportedException(); } @@ -343,8 +340,7 @@ namespace System.Diagnostics.Tracing uint ret = 0; // Check if this property is a nested struct. - InvokeTypeInfo invokeTypeInfo = property.typeInfo as InvokeTypeInfo; - if(invokeTypeInfo != null) + if(property.typeInfo is InvokeTypeInfo invokeTypeInfo) { // Each nested struct is serialized as: // TypeCode.Object : 4 bytes diff --git a/src/System.Private.CoreLib/src/System/Exception.cs b/src/System.Private.CoreLib/src/System/Exception.cs index 1bb73b4d0e..bfdd601802 100644 --- a/src/System.Private.CoreLib/src/System/Exception.cs +++ b/src/System.Private.CoreLib/src/System/Exception.cs @@ -200,8 +200,7 @@ namespace System { if (Data.Contains("__RestrictedErrorObject")) { - __RestrictedErrorObject restrictedObject = Data["__RestrictedErrorObject"] as __RestrictedErrorObject; - if (restrictedObject != null) + if (Data["__RestrictedErrorObject"] is __RestrictedErrorObject restrictedObject) restrictedErrorObject = restrictedObject.RealErrorObject; } return (bool)Data["__HasRestrictedLanguageErrorObject"]; diff --git a/src/System.Private.CoreLib/src/System/MulticastDelegate.cs b/src/System.Private.CoreLib/src/System/MulticastDelegate.cs index fe4283bdc5..40f9478c64 100644 --- a/src/System.Private.CoreLib/src/System/MulticastDelegate.cs +++ b/src/System.Private.CoreLib/src/System/MulticastDelegate.cs @@ -233,8 +233,7 @@ namespace System followCount = (int)dFollow._invocationCount; int resultCount; - object[] invocationList = _invocationList as object[]; - if (invocationList == null) + if (!(_invocationList is object[] invocationList)) { resultCount = 1 + followCount; resultList = new object[resultCount]; @@ -343,10 +342,9 @@ namespace System if (v == null) return this; - if (v._invocationList as object[] == null) + if (!(v._invocationList is object[])) { - object[] invocationList = _invocationList as object[]; - if (invocationList == null) + if (!(_invocationList is object[] invocationList)) { // they are both not real Multicast if (this.Equals(value)) @@ -375,8 +373,7 @@ namespace System } else { - object[] invocationList = _invocationList as object[]; - if (invocationList != null) + if (_invocationList is object[] invocationList) { int invocationCount = (int)_invocationCount; int vInvocationCount = (int)v._invocationCount; @@ -411,8 +408,7 @@ namespace System public override sealed Delegate[] GetInvocationList() { Delegate[] del; - object[] invocationList = _invocationList as object[]; - if (invocationList == null) + if (!(_invocationList is object[] invocationList)) { del = new Delegate[1]; del[0] = this; @@ -468,17 +464,14 @@ namespace System if (_invocationCount != (IntPtr)0) { - var t = _invocationList as Delegate; - - if (t != null) + if (_invocationList is Delegate t) { // this is a secure/wrapper delegate so we need to unwrap and check the inner one return t.GetHashCode(); } } - object[] invocationList = _invocationList as object[]; - if (invocationList == null) + if (!(_invocationList is object[] invocationList)) { return base.GetHashCode(); } @@ -510,16 +503,14 @@ namespace System } else { - object[] invocationList = _invocationList as object[]; - if (invocationList != null) + if (_invocationList is object[] invocationList) { int invocationCount = (int)_invocationCount; return ((Delegate)invocationList[invocationCount - 1]).GetTarget(); } else { - Delegate receiver = _invocationList as Delegate; - if (receiver != null) + if (_invocationList is Delegate receiver) return receiver.GetTarget(); } } @@ -532,8 +523,7 @@ namespace System if (_invocationCount != (IntPtr)0 && _invocationList != null) { // multicast case - object[] invocationList = _invocationList as object[]; - if (invocationList != null) + if (_invocationList is object[] invocationList) { int index = (int)_invocationCount - 1; return ((Delegate)invocationList[index]).Method; diff --git a/src/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs b/src/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs index ec1a51064e..0160fce4f0 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs @@ -822,24 +822,21 @@ namespace System.Reflection.Emit return; } - GenericMethodInfo gmi = handle as GenericMethodInfo; - if (gmi != null) + if (handle is GenericMethodInfo gmi) { methodHandle = gmi.m_methodHandle.Value; typeHandle = gmi.m_context.Value; return; } - GenericFieldInfo gfi = handle as GenericFieldInfo; - if (gfi != null) + if (handle is GenericFieldInfo gfi) { fieldHandle = gfi.m_fieldHandle.Value; typeHandle = gfi.m_context.Value; return; } - VarArgMethod vaMeth = handle as VarArgMethod; - if (vaMeth != null) + if (handle is VarArgMethod vaMeth) { if (vaMeth.m_dynamicMethod == null) { @@ -949,9 +946,7 @@ namespace System.Reflection.Emit if (fromMethod == 0) return (byte[])this[token]; - VarArgMethod vaMethod = this[token] as VarArgMethod; - - if (vaMethod == null) + if (!(this[token] is VarArgMethod vaMethod)) return null; return vaMethod.m_signature.GetSignature(true); diff --git a/src/System.Private.CoreLib/src/System/Resources/ResourceManager.cs b/src/System.Private.CoreLib/src/System/Resources/ResourceManager.cs index 8d72e5e096..d216db4bc7 100644 --- a/src/System.Private.CoreLib/src/System/Resources/ResourceManager.cs +++ b/src/System.Private.CoreLib/src/System/Resources/ResourceManager.cs @@ -1002,8 +1002,7 @@ namespace System.Resources if (value != null) { - UnmanagedMemoryStream stream = value as UnmanagedMemoryStream; - if (stream != null && wrapUnmanagedMemStream) + if (value is UnmanagedMemoryStream stream && wrapUnmanagedMemStream) return new UnmanagedMemoryStreamWrapper(stream); else return value; @@ -1041,8 +1040,7 @@ namespace System.Resources } } - UnmanagedMemoryStream stream = value as UnmanagedMemoryStream; - if (stream != null && wrapUnmanagedMemStream) + if (value is UnmanagedMemoryStream stream && wrapUnmanagedMemStream) return new UnmanagedMemoryStreamWrapper(stream); else return value; diff --git a/src/System.Private.CoreLib/src/System/RtType.cs b/src/System.Private.CoreLib/src/System/RtType.cs index 7327c469c6..c1ace86f6a 100644 --- a/src/System.Private.CoreLib/src/System/RtType.cs +++ b/src/System.Private.CoreLib/src/System/RtType.cs @@ -4957,10 +4957,8 @@ namespace System.Reflection private static int GetHashCodeHelper(K key) { - string sKey = key as string; - // For strings we don't want the key to differ across domains as CerHashtable might be shared. - if (sKey == null) + if (!(key is string sKey)) { return key.GetHashCode(); } diff --git a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs index cfd45f6286..a4c0f79074 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs @@ -736,8 +736,7 @@ namespace System.Runtime.CompilerServices Task task = this.Task; // If the exception represents cancellation, cancel the task. Otherwise, fault the task. - var oce = exception as OperationCanceledException; - bool successfullySet = oce != null ? + bool successfullySet = exception is OperationCanceledException oce ? task.TrySetCanceled(oce.CancellationToken, oce) : task.TrySetException(exception); diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs index 972b28977d..93b7cdd3d4 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs @@ -310,8 +310,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // Make sure we have an array to begin with - Array dataArray = _data as Array; - if (dataArray == null) + if (!(_data is Array dataArray)) { throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, typeof (T).MakeArrayType().Name), HResults.TYPE_E_TYPEMISMATCH); } @@ -400,8 +399,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // If the property type is IInspectable, and we have a nested IPropertyValue, then we need // to pass along the request to coerce the value. - IPropertyValue ipv = value as IPropertyValue; - if (type == PropertyType.Inspectable && ipv != null) + if (type == PropertyType.Inspectable && value is IPropertyValue ipv) { if (typeof(T) == typeof(byte)) { @@ -507,8 +505,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime Debug.Assert(expectedArrayElementType != null); Debug.Assert(Marshal.SizeOf(expectedArrayElementType) == Marshal.SizeOf(typeof(T))); - Array dataArray = _data as Array; - if (dataArray == null || _data.GetType().GetElementType() != expectedArrayElementType) + if (!(_data is Array dataArray) || _data.GetType().GetElementType() != expectedArrayElementType) { throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, _data.GetType(), expectedArrayElementType.MakeArrayType().Name), HResults.TYPE_E_TYPEMISMATCH); } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs index 5a19e0d927..634963e7b3 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs @@ -91,8 +91,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime private object InvokeInternal(object target, object[] args, bool getValue) { // Forward to the right object if we are dealing with a proxy - IGetProxyTarget proxy = target as IGetProxyTarget; - if (proxy != null) + if (target is IGetProxyTarget proxy) { target = proxy.GetTarget(); } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs index 3f6fbaa80b..53a889e651 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs @@ -71,8 +71,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Note: This dictionary is not really read-only - you could QI for a modifiable // dictionary. We gain some perf by doing this. We believe this is acceptable. - IReadOnlyDictionary roDictionary = _this as IReadOnlyDictionary; - if (roDictionary == null) + if (!(_this is IReadOnlyDictionary roDictionary)) { roDictionary = new ReadOnlyDictionary(_this); } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs index bcc8590bb2..56cc2f6a4d 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs @@ -31,8 +31,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime Debug.Assert(target != null); Debug.Assert(propertyName != null); - IGetProxyTarget proxy = target as IGetProxyTarget; - if (proxy != null) + if (target is IGetProxyTarget proxy) target = proxy.GetTarget(); // Only return public instance/static properties @@ -66,8 +65,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime Debug.Assert(target != null); Debug.Assert(propertyName != null); - IGetProxyTarget proxy = target as IGetProxyTarget; - if (proxy != null) + if (target is IGetProxyTarget proxy) target = proxy.GetTarget(); // Only return public instance/static properties @@ -88,8 +86,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal static unsafe void GetType(object target, TypeNameNative* pIndexedParamType) { - IGetProxyTarget proxy = target as IGetProxyTarget; - if (proxy != null) + if (target is IGetProxyTarget proxy) target = proxy.GetTarget(); SystemTypeMarshaler.ConvertToNative(target.GetType(), pIndexedParamType); @@ -156,22 +153,22 @@ namespace System.Runtime.InteropServices.WindowsRuntime // // QI and figure out the right flags // - if (target as IList != null) + if (target is IList) supportFlags |= InterfaceForwardingSupport.IBindableVector; // NOTE: We need to use the directed type here // If we use IVector_Raw here, it derives from a different IIterable which the runtime // doesn't recognize, and therefore IEnumerable cast won't be able to take advantage of this QI - if (target as IList != null) + if (target is IList) supportFlags |= InterfaceForwardingSupport.IVector; - if (target as IBindableVectorView != null) + if (target is IBindableVectorView) supportFlags |= InterfaceForwardingSupport.IBindableVectorView; // NOTE: We need to use the redirected type here // If we use IVector_Raw here, it derives from a different IIterable which the runtime // doesn't recognize, and therefore IEnumerable cast won't be able to take advantage of this QI - if (target as IReadOnlyList != null) + if (target is IReadOnlyList) supportFlags |= InterfaceForwardingSupport.IVectorView; // Verify IEnumerable last because the first few QIs might succeed and we need @@ -179,7 +176,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // forward it manually) // For example, if we try to shoot in the dark by trying IVector and it // succeeded, IEnumerable needs to know that - if (target as IEnumerable != null) + if (target is IEnumerable) supportFlags |= InterfaceForwardingSupport.IBindableIterableOrIIterable; return new ICustomPropertyProviderProxy(target, supportFlags); diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs index 4e06ae03e5..01e8f7b44c 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs @@ -74,9 +74,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime return; } - ConstantSplittableMap splittableMap = _this as ConstantSplittableMap; - - if (splittableMap == null) + if (!(_this is ConstantSplittableMap splittableMap)) splittableMap = new ConstantSplittableMap(_this); splittableMap.Split(out first, out second); diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs index b6260dc52e..657eac0bfc 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs @@ -63,8 +63,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Note: This list is not really read-only - you could QI for a modifiable // list. We gain some perf by doing this. We believe this is acceptable. - IReadOnlyList roList = _this as IReadOnlyList; - if (roList == null) + if (!(_this is IReadOnlyList roList)) { roList = new ReadOnlyCollection(_this); } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs index 2ec85bb3f0..487ebd160a 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs @@ -38,8 +38,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { object _this = Unsafe.As(this); - IMap _this_map = _this as IMap; - if (_this_map != null) + if (_this is IMap _this_map) { uint size = _this_map.Size; @@ -75,8 +74,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { object _this = Unsafe.As(this); - IDictionary _this_dictionary = _this as IDictionary; - if (_this_dictionary != null) + if (_this is IDictionary _this_dictionary) { _this_dictionary.Add(item.Key, item.Value); } @@ -92,8 +90,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { object _this = Unsafe.As(this); - IMap _this_map = _this as IMap; - if (_this_map != null) + if (_this is IMap _this_map) { _this_map.Clear(); } @@ -109,8 +106,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { object _this = Unsafe.As(this); - IDictionary _this_dictionary = _this as IDictionary; - if (_this_dictionary != null) + if (_this is IDictionary _this_dictionary) { V value; bool hasKey = _this_dictionary.TryGetValue(item.Key, out value); @@ -157,8 +153,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { object _this = Unsafe.As(this); - IDictionary _this_dictionary = _this as IDictionary; - if (_this_dictionary != null) + if (_this is IDictionary _this_dictionary) { return _this_dictionary.Remove(item.Key); } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs index 880bffb623..290f927d0d 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs @@ -38,8 +38,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { object _this = Unsafe.As(this); - IMapView _this_map = _this as IMapView; - if (_this_map != null) + if (_this is IMapView _this_map) { uint size = _this_map.Size; diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs index fdc0d22632..2a6208f1bb 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs @@ -32,13 +32,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime { internal static string ToString(object obj) { - IGetProxyTarget proxy = obj as IGetProxyTarget; - if (proxy != null) + if (obj is IGetProxyTarget proxy) obj = proxy.GetTarget(); // Check whether the type implements IStringable. - IStringable stringableType = obj as IStringable; - if (stringableType != null) + if (obj is IStringable stringableType) { return stringableType.ToString(); } @@ -80,8 +78,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public override string ToString() { // Check whether the type implements IStringable. - IStringable stringableType = this as IStringable; - if (stringableType != null) + if (this is IStringable stringableType) { return stringableType.ToString(); } diff --git a/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs b/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs index d4ff9b1ef5..5e1e093de9 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs @@ -673,8 +673,7 @@ namespace System.Threading.Tasks var targetTask = o as Task; if (targetTask == null) { - var tuple = o as Tuple; - if (tuple != null) + if (o is Tuple tuple) { targetTask = tuple.Item1; @@ -2499,14 +2498,13 @@ namespace System.Threading.Tasks { // Invoke the delegate Debug.Assert(m_action != null, "Null action in InnerInvoke()"); - var action = m_action as Action; - if (action != null) + if (m_action is Action action) { action(); return; } - var actionWithState = m_action as Action; - if (actionWithState != null) + + if (m_action is Action actionWithState) { actionWithState(m_stateObject); return; @@ -2523,8 +2521,7 @@ namespace System.Threading.Tasks { Debug.Assert(unhandledException != null); - OperationCanceledException exceptionAsOce = unhandledException as OperationCanceledException; - if (exceptionAsOce != null && IsCancellationRequested && + if (unhandledException is OperationCanceledException exceptionAsOce && IsCancellationRequested && m_contingentProperties.m_cancellationToken == exceptionAsOce.CancellationToken) { // All conditions are satisfied for us to go into canceled state in Finish(). @@ -4431,9 +4428,7 @@ namespace System.Threading.Tasks // Task is completed. Nothing to do here. if (continuationsLocalRef == s_taskCompletionSentinel) return; - List continuationsLocalListRef = continuationsLocalRef as List; - - if (continuationsLocalListRef == null) + if (!(continuationsLocalRef is List continuationsLocalListRef)) { // This is not a list. If we have a single object (the one we want to remove) we try to replace it with an empty list. // Note we cannot go back to a null state, since it will mess up the AddTaskContinuation logic. @@ -5524,15 +5519,13 @@ namespace System.Threading.Tasks public static Task WhenAll(IEnumerable tasks) { // Take a more efficient path if tasks is actually an array - Task[] taskArray = tasks as Task[]; - if (taskArray != null) + if (tasks is Task[] taskArray) { return WhenAll(taskArray); } // Skip a List allocation/copy if tasks is a collection - ICollection taskCollection = tasks as ICollection; - if (taskCollection != null) + if (tasks is ICollection taskCollection) { int index = 0; taskArray = new Task[taskCollection.Count]; @@ -5774,15 +5767,13 @@ namespace System.Threading.Tasks public static Task WhenAll(IEnumerable> tasks) { // Take a more efficient route if tasks is actually an array - Task[] taskArray = tasks as Task[]; - if (taskArray != null) + if (tasks is Task[] taskArray) { return WhenAll(taskArray); } // Skip a List allocation/copy if tasks is a collection - ICollection> taskCollection = tasks as ICollection>; - if (taskCollection != null) + if (tasks is ICollection> taskCollection) { int index = 0; taskArray = new Task[taskCollection.Count]; @@ -6148,20 +6139,17 @@ namespace System.Threading.Tasks { if (continuationObject != null) { - Action singleAction = continuationObject as Action; - if (singleAction != null) + if (continuationObject is Action singleAction) { return new Delegate[] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(singleAction) }; } - TaskContinuation taskContinuation = continuationObject as TaskContinuation; - if (taskContinuation != null) + if (continuationObject is TaskContinuation taskContinuation) { return taskContinuation.GetDelegateContinuationsForDebugger(); } - Task continuationTask = continuationObject as Task; - if (continuationTask != null) + if (continuationObject is Task continuationTask) { Debug.Assert(continuationTask.m_action == null); Delegate[] delegates = continuationTask.GetDelegateContinuationsForDebugger(); @@ -6171,14 +6159,12 @@ namespace System.Threading.Tasks //We need this ITaskCompletionAction after the Task because in the case of UnwrapPromise //the VS debugger is more interested in the continuation than the internal invoke() - ITaskCompletionAction singleCompletionAction = continuationObject as ITaskCompletionAction; - if (singleCompletionAction != null) + if (continuationObject is ITaskCompletionAction singleCompletionAction) { return new Delegate[] { new Action(singleCompletionAction.Invoke) }; } - List continuationList = continuationObject as List; - if (continuationList != null) + if (continuationObject is List continuationList) { List result = new List(); foreach (object obj in continuationList) @@ -6628,8 +6614,7 @@ namespace System.Threading.Tasks // Otherwise, process the inner task it returned. case TaskStatus.RanToCompletion: - var taskOfTaskOfTResult = task as Task>; // it's either a Task or Task> - ProcessInnerTask(taskOfTaskOfTResult != null ? + ProcessInnerTask(task is Task> taskOfTaskOfTResult ? // it's either a Task or Task> taskOfTaskOfTResult.Result : ((Task)task).Result); break; } diff --git a/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskContinuation.cs b/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskContinuation.cs index da5ba8541a..e7a7060e49 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskContinuation.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskContinuation.cs @@ -53,14 +53,13 @@ namespace System.Threading.Tasks // Invoke the delegate Debug.Assert(m_action != null); - var action = m_action as Action; - if (action != null) + if (m_action is Action action) { action(antecedent); return; } - var actionWithState = m_action as Action; - if (actionWithState != null) + + if (m_action is Action actionWithState) { actionWithState(antecedent, m_stateObject); return; @@ -100,14 +99,13 @@ namespace System.Threading.Tasks // Invoke the delegate Debug.Assert(m_action != null); - var func = m_action as Func; - if (func != null) + if (m_action is Func func) { m_result = func(antecedent); return; } - var funcWithState = m_action as Func; - if (funcWithState != null) + + if (m_action is Func funcWithState) { m_result = funcWithState(antecedent, m_stateObject); return; @@ -147,14 +145,13 @@ namespace System.Threading.Tasks // Invoke the delegate Debug.Assert(m_action != null); - var action = m_action as Action>; - if (action != null) + if (m_action is Action> action) { action(antecedent); return; } - var actionWithState = m_action as Action, object>; - if (actionWithState != null) + + if (m_action is Action, object> actionWithState) { actionWithState(antecedent, m_stateObject); return; @@ -194,14 +191,13 @@ namespace System.Threading.Tasks // Invoke the delegate Debug.Assert(m_action != null); - var func = m_action as Func, TResult>; - if (func != null) + if (m_action is Func, TResult> func) { m_result = func(antecedent); return; } - var funcWithState = m_action as Func, object, TResult>; - if (funcWithState != null) + + if (m_action is Func, object, TResult> funcWithState) { m_result = funcWithState(antecedent, m_stateObject); return; diff --git a/src/System.Private.CoreLib/src/System/Variant.cs b/src/System.Private.CoreLib/src/System/Variant.cs index 5d781476c6..385a44ffba 100644 --- a/src/System.Private.CoreLib/src/System/Variant.cs +++ b/src/System.Private.CoreLib/src/System/Variant.cs @@ -530,8 +530,7 @@ namespace System // updated object back to the original type. internal static void MarshalHelperCastVariant(object pValue, int vt, ref Variant v) { - IConvertible iv = pValue as IConvertible; - if (iv == null) + if (!(pValue is IConvertible iv)) { switch (vt) { -- cgit v1.2.3