(C#7) Use pattern matching `is` rather than `as` with null check (#21828)
authorBen Adams <thundercat@illyriad.co.uk>
Sun, 6 Jan 2019 01:49:58 +0000 (02:49 +0100)
committerJan Kotas <jkotas@microsoft.com>
Sun, 6 Jan 2019 01:49:58 +0000 (17:49 -0800)
* Use pattern matching `is` rather than `as` with null check

62 files changed:
src/System.Private.CoreLib/shared/System/AggregateException.cs
src/System.Private.CoreLib/shared/System/AppContext.cs
src/System.Private.CoreLib/shared/System/Collections/Comparer.cs
src/System.Private.CoreLib/shared/System/Collections/CompatibleComparer.cs
src/System.Private.CoreLib/shared/System/Collections/Concurrent/ConcurrentQueue.cs
src/System.Private.CoreLib/shared/System/Collections/ObjectModel/Collection.cs
src/System.Private.CoreLib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs
src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs
src/System.Private.CoreLib/shared/System/ComponentModel/EditorBrowsableAttribute.cs
src/System.Private.CoreLib/shared/System/Convert.cs
src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs
src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.cs
src/System.Private.CoreLib/shared/System/Globalization/CultureInfo.cs
src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.cs
src/System.Private.CoreLib/shared/System/Globalization/RegionInfo.cs
src/System.Private.CoreLib/shared/System/Globalization/SortKey.cs
src/System.Private.CoreLib/shared/System/Globalization/StringInfo.cs
src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs
src/System.Private.CoreLib/shared/System/IO/FileStreamCompletionSource.Win32.cs
src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs
src/System.Private.CoreLib/shared/System/IO/Stream.cs
src/System.Private.CoreLib/shared/System/IO/TextWriter.cs
src/System.Private.CoreLib/shared/System/String.Comparison.cs
src/System.Private.CoreLib/shared/System/StringComparer.cs
src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs
src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs
src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs
src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs
src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs
src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs
src/System.Private.CoreLib/shared/System/Text/Encoding.cs
src/System.Private.CoreLib/shared/System/Text/EncodingInfo.cs
src/System.Private.CoreLib/shared/System/Text/UTF32Encoding.cs
src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs
src/System.Private.CoreLib/shared/System/Text/UTF8Encoding.cs
src/System.Private.CoreLib/shared/System/Text/UnicodeEncoding.cs
src/System.Private.CoreLib/shared/System/Threading/Tasks/Future.cs
src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskExceptionHolder.cs
src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskScheduler.cs
src/System.Private.CoreLib/shared/System/TimeZoneInfo.Win32.cs
src/System.Private.CoreLib/shared/System/Tuple.cs
src/System.Private.CoreLib/src/System/Array.cs
src/System.Private.CoreLib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs
src/System.Private.CoreLib/src/System/Diagnostics/Eventing/EventPipeMetadataGenerator.cs
src/System.Private.CoreLib/src/System/Exception.cs
src/System.Private.CoreLib/src/System/MulticastDelegate.cs
src/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs
src/System.Private.CoreLib/src/System/Resources/ResourceManager.cs
src/System.Private.CoreLib/src/System/RtType.cs
src/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs
src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs
src/System.Private.CoreLib/src/System/Threading/Tasks/TaskContinuation.cs
src/System.Private.CoreLib/src/System/Variant.cs

index 022a1ea..048005c 100644 (file)
@@ -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);
                     }
index 9df7c8d..c3994ea 100644 (file)
@@ -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;
             }
index e22fb5b..24a6cbf 100644 (file)
@@ -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);
index 587fd68..5342dcd 100644 (file)
@@ -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);
             }
index f3634e8..17e7fd5 100644 (file)
@@ -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<T>;
-            if (c != null)
+            if (collection is ICollection<T> 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;
index 9efd671..c96a157 100644 (file)
@@ -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;
                 }
index 584b4cc..9d463da 100644 (file)
@@ -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);
             }
index 5f7108a..d506ffa 100644 (file)
@@ -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)
                 {
index 9b4d6e6..a59ee83 100644 (file)
@@ -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()
index 077dda9..2bc0179 100644 (file)
@@ -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();
         }
index 3dc1cb0..8159bad 100644 (file)
@@ -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;
index 21fd721..9f7669e 100644 (file)
@@ -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;
             }
index f3f56dd..1535126 100644 (file)
@@ -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)
index 849602a..56f38ff 100644 (file)
@@ -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;
         }
index 8416257..576672b 100644 (file)
@@ -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);
             }
index 9624946..f9c7f68 100644 (file)
@@ -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;
             }
index 936a3cb..425e6f2 100644 (file)
@@ -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));
             }
index 61e2160..77964fb 100644 (file)
@@ -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);
             }
index ec499d8..a7996fd 100644 (file)
@@ -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");
index 8ca162b..b9f2b5e 100644 (file)
@@ -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
index fe9f9fe..537d28c 100644 (file)
@@ -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)
index e470517..030a015 100644 (file)
@@ -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));
                 }
index 360167d..5bae67b 100644 (file)
@@ -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)
index e4378c5..8fab833 100644 (file)
@@ -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;
             }
index 8c62730..d94554c 100644 (file)
@@ -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);
             }
index 56c0047..0525861 100644 (file)
@@ -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);
             }
index a97baf0..2af0d12 100644 (file)
@@ -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);
             }
index 4aab3f6..c3d07c9 100644 (file)
@@ -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);
             }
index 92afcf7..077d927 100644 (file)
@@ -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);
             }
index 760c280..cfce410 100644 (file)
@@ -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);
             }
index c1b6496..175e544 100644 (file)
@@ -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));
index b8d634c..002d9ef 100644 (file)
@@ -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;
             }
index d579cc9..02f3167 100644 (file)
@@ -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) &&
index 5c51c81..a932778 100644 (file)
@@ -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)) &&
index 426835e..5e1b9ae 100644 (file)
@@ -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)) &&
index d80c229..870962c 100644 (file)
@@ -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),
index e3339ef..5cc0b67 100644 (file)
@@ -597,14 +597,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();
                 return;
             }
-            var funcWithState = m_action as Func<object, TResult>;
-            if (funcWithState != null)
+
+            if (m_action is Func<object, TResult> funcWithState)
             {
                 m_result = funcWithState(m_stateObject);
                 return;
index 0037923..cdf5c78 100644 (file)
@@ -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<Exception>;
-                    if (exColl != null)
+                    if (exceptionObject is IEnumerable<Exception> 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<ExceptionDispatchInfo>;
-                        if (ediColl != null)
+                        if (exceptionObject is IEnumerable<ExceptionDispatchInfo> ediColl)
                         {
                             exceptions.AddRange(ediColl);
 #if DEBUG
index c5bf02b..13257b3 100644 (file)
@@ -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<Task>(activeTasksSource)).ToArray();
             }
index a16f6a8..a7095de 100644 (file)
@@ -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;
index ebbd156..bb72e4f 100644 (file)
@@ -124,9 +124,7 @@ namespace System
         {
             if (other == null) return false;
 
-            Tuple<T1> objTuple = other as Tuple<T1>;
-
-            if (objTuple == null)
+            if (!(other is Tuple<T1> objTuple))
             {
                 return false;
             }
@@ -143,9 +141,7 @@ namespace System
         {
             if (other == null) return 1;
 
-            Tuple<T1> objTuple = other as Tuple<T1>;
-
-            if (objTuple == null)
+            if (!(other is Tuple<T1> 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<T1, T2> objTuple = other as Tuple<T1, T2>;
-
-            if (objTuple == null)
+            if (!(other is Tuple<T1, T2> objTuple))
             {
                 return false;
             }
@@ -246,9 +240,7 @@ namespace System
         {
             if (other == null) return 1;
 
-            Tuple<T1, T2> objTuple = other as Tuple<T1, T2>;
-
-            if (objTuple == null)
+            if (!(other is Tuple<T1, T2> 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<T1, T2, T3> objTuple = other as Tuple<T1, T2, T3>;
-
-            if (objTuple == null)
+            if (!(other is Tuple<T1, T2, T3> objTuple))
             {
                 return false;
             }
@@ -364,9 +354,7 @@ namespace System
         {
             if (other == null) return 1;
 
-            Tuple<T1, T2, T3> objTuple = other as Tuple<T1, T2, T3>;
-
-            if (objTuple == null)
+            if (!(other is Tuple<T1, T2, T3> 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<T1, T2, T3, T4> objTuple = other as Tuple<T1, T2, T3, T4>;
-
-            if (objTuple == null)
+            if (!(other is Tuple<T1, T2, T3, T4> objTuple))
             {
                 return false;
             }
@@ -493,9 +479,7 @@ namespace System
         {
             if (other == null) return 1;
 
-            Tuple<T1, T2, T3, T4> objTuple = other as Tuple<T1, T2, T3, T4>;
-
-            if (objTuple == null)
+            if (!(other is Tuple<T1, T2, T3, T4> 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<T1, T2, T3, T4, T5> objTuple = other as Tuple<T1, T2, T3, T4, T5>;
-
-            if (objTuple == null)
+            if (!(other is Tuple<T1, T2, T3, T4, T5> objTuple))
             {
                 return false;
             }
@@ -633,9 +615,7 @@ namespace System
         {
             if (other == null) return 1;
 
-            Tuple<T1, T2, T3, T4, T5> objTuple = other as Tuple<T1, T2, T3, T4, T5>;
-
-            if (objTuple == null)
+            if (!(other is Tuple<T1, T2, T3, T4, T5> 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<T1, T2, T3, T4, T5, T6> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6>;
-
-            if (objTuple == null)
+            if (!(other is Tuple<T1, T2, T3, T4, T5, T6> objTuple))
             {
                 return false;
             }
@@ -784,9 +762,7 @@ namespace System
         {
             if (other == null) return 1;
 
-            Tuple<T1, T2, T3, T4, T5, T6> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6>;
-
-            if (objTuple == null)
+            if (!(other is Tuple<T1, T2, T3, T4, T5, T6> 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<T1, T2, T3, T4, T5, T6, T7> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7>;
-
-            if (objTuple == null)
+            if (!(other is Tuple<T1, T2, T3, T4, T5, T6, T7> objTuple))
             {
                 return false;
             }
@@ -946,9 +920,7 @@ namespace System
         {
             if (other == null) return 1;
 
-            Tuple<T1, T2, T3, T4, T5, T6, T7> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7>;
-
-            if (objTuple == null)
+            if (!(other is Tuple<T1, T2, T3, T4, T5, T6, T7> 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<T1, T2, T3, T4, T5, T6, T7, TRest> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>;
-
-            if (objTuple == null)
+            if (!(other is Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> objTuple))
             {
                 return false;
             }
@@ -1124,9 +1094,7 @@ namespace System
         {
             if (other == null) return 1;
 
-            Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>;
-
-            if (objTuple == null)
+            if (!(other is Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> objTuple))
             {
                 throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), nameof(other));
             }
index 490ef91..41e8d79 100644 (file)
@@ -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<object>(objArray, index, length);
             }
index 29446b2..998fa64 100644 (file)
@@ -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<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[];
-            if (pairs != null)
+            if (array is KeyValuePair<TKey, TValue>[] 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<T> 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);
             }
index 06aa854..991b818 100644 (file)
@@ -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
index 1bb73b4..bfdd601 100644 (file)
@@ -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"];
index fe4283b..40f9478 100644 (file)
@@ -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;
index ec1a510..0160fce 100644 (file)
@@ -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);
index 8d72e5e..d216db4 100644 (file)
@@ -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;
index 7327c46..c1ace86 100644 (file)
@@ -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();
             }
index cfd45f6..a4c0f79 100644 (file)
@@ -736,8 +736,7 @@ namespace System.Runtime.CompilerServices
             Task<TResult> 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);
 
index 972b289..93b7cdd 100644 (file)
@@ -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);
             }
index 5a19e0d..634963e 100644 (file)
@@ -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();
             }
index 3f6fbaa..53a889e 100644 (file)
@@ -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<K, V> roDictionary = _this as IReadOnlyDictionary<K, V>;
-            if (roDictionary == null)
+            if (!(_this is IReadOnlyDictionary<K, V> roDictionary))
             {
                 roDictionary = new ReadOnlyDictionary<K, V>(_this);
             }
index bcc8590..56cc2f6 100644 (file)
@@ -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<T1> here, it derives from a different IIterable<T> which the runtime
             // doesn't recognize, and therefore IEnumerable cast won't be able to take advantage of this QI
-            if (target as IList<T1> != null)
+            if (target is IList<T1>)
                 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<T1> here, it derives from a different IIterable<T> which the runtime
             // doesn't recognize, and therefore IEnumerable cast won't be able to take advantage of this QI
-            if (target as IReadOnlyList<T2> != null)
+            if (target is IReadOnlyList<T2>)
                 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<IInspectable> and it 
             // succeeded, IEnumerable needs to know that
-            if (target as IEnumerable != null)
+            if (target is IEnumerable)
                 supportFlags |= InterfaceForwardingSupport.IBindableIterableOrIIterable;
 
             return new ICustomPropertyProviderProxy<T1, T2>(target, supportFlags);
index 4e06ae0..01e8f7b 100644 (file)
@@ -74,9 +74,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 return;
             }
 
-            ConstantSplittableMap<K, V> splittableMap = _this as ConstantSplittableMap<K, V>;
-
-            if (splittableMap == null)
+            if (!(_this is ConstantSplittableMap<K, V> splittableMap))
                 splittableMap = new ConstantSplittableMap<K, V>(_this);
 
             splittableMap.Split(out first, out second);
index b6260dc..657eac0 100644 (file)
@@ -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<T> roList = _this as IReadOnlyList<T>;
-            if (roList == null)
+            if (!(_this is IReadOnlyList<T> roList))
             {
                 roList = new ReadOnlyCollection<T>(_this);
             }
index 2ec85bb..487ebd1 100644 (file)
@@ -38,8 +38,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         {
             object _this = Unsafe.As<object>(this);
 
-            IMap<K, V> _this_map = _this as IMap<K, V>;
-            if (_this_map != null)
+            if (_this is IMap<K, V> _this_map)
             {
                 uint size = _this_map.Size;
 
@@ -75,8 +74,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         {
             object _this = Unsafe.As<object>(this);
 
-            IDictionary<K, V> _this_dictionary = _this as IDictionary<K, V>;
-            if (_this_dictionary != null)
+            if (_this is IDictionary<K, V> _this_dictionary)
             {
                 _this_dictionary.Add(item.Key, item.Value);
             }
@@ -92,8 +90,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         {
             object _this = Unsafe.As<object>(this);
 
-            IMap<K, V> _this_map = _this as IMap<K, V>;
-            if (_this_map != null)
+            if (_this is IMap<K, V> _this_map)
             {
                 _this_map.Clear();
             }
@@ -109,8 +106,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         {
             object _this = Unsafe.As<object>(this);
 
-            IDictionary<K, V> _this_dictionary = _this as IDictionary<K, V>;
-            if (_this_dictionary != null)
+            if (_this is IDictionary<K, V> _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<object>(this);
 
-            IDictionary<K, V> _this_dictionary = _this as IDictionary<K, V>;
-            if (_this_dictionary != null)
+            if (_this is IDictionary<K, V> _this_dictionary)
             {
                 return _this_dictionary.Remove(item.Key);
             }
index 880bffb..290f927 100644 (file)
@@ -38,8 +38,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         {
             object _this = Unsafe.As<object>(this);
 
-            IMapView<K, V> _this_map = _this as IMapView<K, V>;
-            if (_this_map != null)
+            if (_this is IMapView<K, V> _this_map)
             {
                 uint size = _this_map.Size;
 
index fdc0d22..2a6208f 100644 (file)
@@ -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();
             }
index d4ff9b1..5e1e093 100644 (file)
@@ -673,8 +673,7 @@ namespace System.Threading.Tasks
             var targetTask = o as Task;
             if (targetTask == null)
             {
-                var tuple = o as Tuple<Task, Task, TaskContinuation>;
-                if (tuple != null)
+                if (o is Tuple<Task, Task, TaskContinuation> 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<object>;
-            if (actionWithState != null)
+
+            if (m_action is Action<object> 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<object> continuationsLocalListRef = continuationsLocalRef as List<object>;
-
-            if (continuationsLocalListRef == null)
+            if (!(continuationsLocalRef is List<object> 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<Task> 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<Task> taskCollection = tasks as ICollection<Task>;
-            if (taskCollection != null)
+            if (tasks is ICollection<Task> taskCollection)
             {
                 int index = 0;
                 taskArray = new Task[taskCollection.Count];
@@ -5774,15 +5767,13 @@ namespace System.Threading.Tasks
         public static Task<TResult[]> WhenAll<TResult>(IEnumerable<Task<TResult>> tasks)
         {
             // Take a more efficient route if tasks is actually an array
-            Task<TResult>[] taskArray = tasks as Task<TResult>[];
-            if (taskArray != null)
+            if (tasks is Task<TResult>[] taskArray)
             {
                 return WhenAll<TResult>(taskArray);
             }
 
             // Skip a List allocation/copy if tasks is a collection
-            ICollection<Task<TResult>> taskCollection = tasks as ICollection<Task<TResult>>;
-            if (taskCollection != null)
+            if (tasks is ICollection<Task<TResult>> taskCollection)
             {
                 int index = 0;
                 taskArray = new Task<TResult>[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<Task>(singleCompletionAction.Invoke) };
                 }
 
-                List<object> continuationList = continuationObject as List<object>;
-                if (continuationList != null)
+                if (continuationObject is List<object> continuationList)
                 {
                     List<Delegate> result = new List<Delegate>();
                     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<Task<TResult>>; // it's either a Task<Task> or Task<Task<TResult>>
-                    ProcessInnerTask(taskOfTaskOfTResult != null ?
+                    ProcessInnerTask(task is Task<Task<TResult>> taskOfTaskOfTResult ? // it's either a Task<Task> or Task<Task<TResult>>
                         taskOfTaskOfTResult.Result : ((Task<Task>)task).Result);
                     break;
             }
index da5ba85..e7a7060 100644 (file)
@@ -53,14 +53,13 @@ namespace System.Threading.Tasks
 
             // Invoke the delegate
             Debug.Assert(m_action != null);
-            var action = m_action as Action<Task>;
-            if (action != null)
+            if (m_action is Action<Task> action)
             {
                 action(antecedent);
                 return;
             }
-            var actionWithState = m_action as Action<Task, object>;
-            if (actionWithState != null)
+
+            if (m_action is Action<Task, object> 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<Task, TResult>;
-            if (func != null)
+            if (m_action is Func<Task, TResult> func)
             {
                 m_result = func(antecedent);
                 return;
             }
-            var funcWithState = m_action as Func<Task, object, TResult>;
-            if (funcWithState != null)
+
+            if (m_action is Func<Task, object, TResult> 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<Task<TAntecedentResult>>;
-            if (action != null)
+            if (m_action is Action<Task<TAntecedentResult>> action)
             {
                 action(antecedent);
                 return;
             }
-            var actionWithState = m_action as Action<Task<TAntecedentResult>, object>;
-            if (actionWithState != null)
+
+            if (m_action is Action<Task<TAntecedentResult>, 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<Task<TAntecedentResult>, TResult>;
-            if (func != null)
+            if (m_action is Func<Task<TAntecedentResult>, TResult> func)
             {
                 m_result = func(antecedent);
                 return;
             }
-            var funcWithState = m_action as Func<Task<TAntecedentResult>, object, TResult>;
-            if (funcWithState != null)
+
+            if (m_action is Func<Task<TAntecedentResult>, object, TResult> funcWithState)
             {
                 m_result = funcWithState(antecedent, m_stateObject);
                 return;
index 5d78147..385a44f 100644 (file)
@@ -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)
                 {