Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit d0cdf88

Browse files
benaadamsjkotas
authored andcommitted
(C#7) Use pattern matching is rather than as with null check (#21828)
* Use pattern matching `is` rather than `as` with null check
1 parent 110835b commit d0cdf88

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

62 files changed

+173
-358
lines changed

src/System.Private.CoreLib/shared/System/AggregateException.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -399,11 +399,9 @@ public AggregateException Flatten()
399399
continue;
400400
}
401401

402-
AggregateException currentInnerAsAggregate = currentInnerException as AggregateException;
403-
404402
// If this exception is an aggregate, keep it around for later. Otherwise,
405403
// simply add it to the list of flattened exceptions to be returned.
406-
if (currentInnerAsAggregate != null)
404+
if (currentInnerException is AggregateException currentInnerAsAggregate)
407405
{
408406
exceptionsToFlatten.Add(currentInnerAsAggregate);
409407
}

src/System.Private.CoreLib/shared/System/AppContext.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,8 +99,7 @@ public static bool TryGetSwitch(string switchName, out bool isEnabled)
9999
}
100100
}
101101

102-
string value = GetData(switchName) as string;
103-
if (value != null && bool.TryParse(value, out isEnabled))
102+
if (GetData(switchName) is string value && bool.TryParse(value, out isEnabled))
104103
{
105104
return true;
106105
}

src/System.Private.CoreLib/shared/System/Collections/Comparer.cs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -59,16 +59,13 @@ public int Compare(object a, object b)
5959
if (b == null) return 1;
6060

6161
string sa = a as string;
62-
string sb = b as string;
63-
if (sa != null && sb != null)
62+
if (sa != null && b is string sb)
6463
return _compareInfo.Compare(sa, sb);
6564

66-
IComparable ia = a as IComparable;
67-
if (ia != null)
65+
if (a is IComparable ia)
6866
return ia.CompareTo(b);
6967

70-
IComparable ib = b as IComparable;
71-
if (ib != null)
68+
if (b is IComparable ib)
7269
return -ib.CompareTo(a);
7370

7471
throw new ArgumentException(SR.Argument_ImplementIComparable);

src/System.Private.CoreLib/shared/System/Collections/CompatibleComparer.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,7 @@ public int Compare(object a, object b)
3737
return _comparer.Compare(a, b);
3838
}
3939

40-
IComparable ia = a as IComparable;
41-
if (ia != null)
40+
if (a is IComparable ia)
4241
{
4342
return ia.CompareTo(b);
4443
}

src/System.Private.CoreLib/shared/System/Collections/Concurrent/ConcurrentQueue.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,7 @@ private void InitializeFromCollection(IEnumerable<T> collection)
8080
// case we round its length up to a power of 2, as all segments must
8181
// be a power of 2 in length.
8282
int length = InitialSegmentLength;
83-
var c = collection as ICollection<T>;
84-
if (c != null)
83+
if (collection is ICollection<T> c)
8584
{
8685
int count = c.Count;
8786
if (count > length)
@@ -143,8 +142,7 @@ public ConcurrentQueue(IEnumerable<T> collection)
143142
void ICollection.CopyTo(Array array, int index)
144143
{
145144
// Special-case when the Array is actually a T[], taking a faster path
146-
T[] szArray = array as T[];
147-
if (szArray != null)
145+
if (array is T[] szArray)
148146
{
149147
CopyTo(szArray, index);
150148
return;

src/System.Private.CoreLib/shared/System/Collections/ObjectModel/Collection.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -215,8 +215,7 @@ void ICollection.CopyTo(Array array, int index)
215215
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
216216
}
217217

218-
T[] tArray = array as T[];
219-
if (tArray != null)
218+
if (array is T[] tArray)
220219
{
221220
items.CopyTo(tArray, index);
222221
}
@@ -294,8 +293,7 @@ bool IList.IsFixedSize
294293
// readonly collections are fixed size, if our internal item
295294
// collection does not implement IList. Note that Array implements
296295
// IList, and therefore T[] and U[] will be fixed-size.
297-
IList list = items as IList;
298-
if (list != null)
296+
if (items is IList list)
299297
{
300298
return list.IsFixedSize;
301299
}

src/System.Private.CoreLib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,7 @@ void ICollection.CopyTo(Array array, int index)
147147
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
148148
}
149149

150-
T[] items = array as T[];
151-
if (items != null)
150+
if (array is T[] items)
152151
{
153152
list.CopyTo(items, index);
154153
}

src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -225,9 +225,7 @@ public override bool Equals(object obj)
225225
return true;
226226
}
227227

228-
DefaultValueAttribute other = obj as DefaultValueAttribute;
229-
230-
if (other != null)
228+
if (obj is DefaultValueAttribute other)
231229
{
232230
if (Value != null)
233231
{

src/System.Private.CoreLib/shared/System/ComponentModel/EditorBrowsableAttribute.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,7 @@ public override bool Equals(object obj)
2828
return true;
2929
}
3030

31-
EditorBrowsableAttribute other = obj as EditorBrowsableAttribute;
32-
33-
return (other != null) && other.browsableState == browsableState;
31+
return (obj is EditorBrowsableAttribute other) && other.browsableState == browsableState;
3432
}
3533

3634
public override int GetHashCode()

src/System.Private.CoreLib/shared/System/Convert.cs

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -160,8 +160,7 @@ private static bool DoAsserts()
160160
public static TypeCode GetTypeCode(object value)
161161
{
162162
if (value == null) return TypeCode.Empty;
163-
IConvertible temp = value as IConvertible;
164-
if (temp != null)
163+
if (value is IConvertible temp)
165164
{
166165
return temp.GetTypeCode();
167166
}
@@ -173,8 +172,7 @@ public static TypeCode GetTypeCode(object value)
173172
public static bool IsDBNull(object value)
174173
{
175174
if (value == System.DBNull.Value) return true;
176-
IConvertible convertible = value as IConvertible;
177-
return convertible != null ? convertible.GetTypeCode() == TypeCode.DBNull : false;
175+
return value is IConvertible convertible ? convertible.GetTypeCode() == TypeCode.DBNull : false;
178176
}
179177

180178
// Converts the given object to the given type. In general, this method is
@@ -201,8 +199,7 @@ public static object ChangeType(object value, TypeCode typeCode, IFormatProvider
201199
return null;
202200
}
203201

204-
IConvertible v = value as IConvertible;
205-
if (v == null)
202+
if (!(value is IConvertible v))
206203
{
207204
throw new InvalidCastException(SR.InvalidCast_IConvertible);
208205
}
@@ -330,8 +327,7 @@ public static object ChangeType(object value, Type conversionType, IFormatProvid
330327
return null;
331328
}
332329

333-
IConvertible ic = value as IConvertible;
334-
if (ic == null)
330+
if (!(value is IConvertible ic))
335331
{
336332
if (value.GetType() == conversionType)
337333
{
@@ -2002,11 +1998,9 @@ public static string ToString(object value)
20021998

20031999
public static string ToString(object value, IFormatProvider provider)
20042000
{
2005-
IConvertible ic = value as IConvertible;
2006-
if (ic != null)
2001+
if (value is IConvertible ic)
20072002
return ic.ToString(provider);
2008-
IFormattable formattable = value as IFormattable;
2009-
if (formattable != null)
2003+
if (value is IFormattable formattable)
20102004
return formattable.ToString(null, provider);
20112005
return value == null ? string.Empty : value.ToString();
20122006
}

src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -403,8 +403,7 @@ public static IEnumerable<EventSource> GetSources()
403403
{
404404
foreach (WeakReference eventSourceRef in EventListener.s_EventSources)
405405
{
406-
EventSource eventSource = eventSourceRef.Target as EventSource;
407-
if (eventSource != null && !eventSource.IsDisposed)
406+
if (eventSourceRef.Target is EventSource eventSource && !eventSource.IsDisposed)
408407
ret.Add(eventSource);
409408
}
410409
}
@@ -2715,8 +2714,7 @@ private void EnsureDescriptorsInitialized()
27152714
// TODO Enforce singleton pattern
27162715
foreach (WeakReference eventSourceRef in EventListener.s_EventSources)
27172716
{
2718-
EventSource eventSource = eventSourceRef.Target as EventSource;
2719-
if (eventSource != null && eventSource.Guid == m_guid && !eventSource.IsDisposed)
2717+
if (eventSourceRef.Target is EventSource eventSource && eventSource.Guid == m_guid && !eventSource.IsDisposed)
27202718
{
27212719
if (eventSource != this)
27222720
{
@@ -4160,8 +4158,7 @@ private static void DisposeOnShutdown(object sender, EventArgs e)
41604158
{
41614159
foreach (var esRef in s_EventSources)
41624160
{
4163-
EventSource es = esRef.Target as EventSource;
4164-
if (es != null)
4161+
if (esRef.Target is EventSource es)
41654162
es.Dispose();
41664163
}
41674164
}
@@ -4181,8 +4178,7 @@ private static void RemoveReferencesToListenerInEventSources(EventListener liste
41814178
// Foreach existing EventSource in the appdomain
41824179
foreach (WeakReference eventSourceRef in s_EventSources)
41834180
{
4184-
EventSource eventSource = eventSourceRef.Target as EventSource;
4185-
if (eventSource != null)
4181+
if (eventSourceRef.Target is EventSource eventSource)
41864182
{
41874183
// Is the first output dispatcher the dispatcher we are removing?
41884184
if (eventSource.m_Dispatchers.m_Listener == listenerToRemove)
@@ -4246,8 +4242,7 @@ internal static void Validate()
42464242
foreach (WeakReference eventSourceRef in s_EventSources)
42474243
{
42484244
id++;
4249-
EventSource eventSource = eventSourceRef.Target as EventSource;
4250-
if (eventSource == null)
4245+
if (!(eventSourceRef.Target is EventSource eventSource))
42514246
continue;
42524247
Debug.Assert(eventSource.m_id == id, "Unexpected event source ID.");
42534248

@@ -4328,8 +4323,7 @@ private void CallBackForExistingEventSources(bool addToListenersList, EventHandl
43284323
for (int i = 0; i < eventSourcesSnapshot.Length; i++)
43294324
{
43304325
WeakReference eventSourceRef = eventSourcesSnapshot[i];
4331-
EventSource eventSource = eventSourceRef.Target as EventSource;
4332-
if (eventSource != null)
4326+
if (eventSourceRef.Target is EventSource eventSource)
43334327
{
43344328
EventSourceCreatedEventArgs args = new EventSourceCreatedEventArgs();
43354329
args.EventSource = eventSource;

src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1371,9 +1371,7 @@ public virtual SortKey GetSortKey(string source)
13711371

13721372
public override bool Equals(object value)
13731373
{
1374-
CompareInfo that = value as CompareInfo;
1375-
1376-
if (that != null)
1374+
if (value is CompareInfo that)
13771375
{
13781376
return this.Name == that.Name;
13791377
}

src/System.Private.CoreLib/shared/System/Globalization/CultureInfo.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -872,9 +872,7 @@ public override bool Equals(object value)
872872
if (object.ReferenceEquals(this, value))
873873
return true;
874874

875-
CultureInfo that = value as CultureInfo;
876-
877-
if (that != null)
875+
if (value is CultureInfo that)
878876
{
879877
// using CompareInfo to verify the data passed through the constructor
880878
// CultureInfo(String cultureName, String textAndCompareCultureName)

src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,9 +145,8 @@ public string GetUnicode(string ascii, int index, int count)
145145

146146
public override bool Equals(object obj)
147147
{
148-
IdnMapping that = obj as IdnMapping;
149148
return
150-
that != null &&
149+
obj is IdnMapping that &&
151150
_allowUnassigned == that._allowUnassigned &&
152151
_useStd3AsciiRules == that._useStd3AsciiRules;
153152
}

src/System.Private.CoreLib/shared/System/Globalization/RegionInfo.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -360,8 +360,7 @@ public virtual string ISOCurrencySymbol
360360
////////////////////////////////////////////////////////////////////////
361361
public override bool Equals(object value)
362362
{
363-
RegionInfo that = value as RegionInfo;
364-
if (that != null)
363+
if (value is RegionInfo that)
365364
{
366365
return this.Name.Equals(that.Name);
367366
}

src/System.Private.CoreLib/shared/System/Globalization/SortKey.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,9 +135,7 @@ public static int Compare(SortKey sortkey1, SortKey sortkey2)
135135
////////////////////////////////////////////////////////////////////////
136136
public override bool Equals(object value)
137137
{
138-
SortKey that = value as SortKey;
139-
140-
if (that != null)
138+
if (value is SortKey that)
141139
{
142140
return Compare(this, that) == 0;
143141
}

src/System.Private.CoreLib/shared/System/Globalization/StringInfo.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,7 @@ public StringInfo(string value)
3434

3535
public override bool Equals(object value)
3636
{
37-
StringInfo that = value as StringInfo;
38-
if (that != null)
37+
if (value is StringInfo that)
3938
{
4039
return (_str.Equals(that._str));
4140
}

src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -654,9 +654,7 @@ private void PopulateIsAsciiCasingSameAsInvariant()
654654
////////////////////////////////////////////////////////////////////////
655655
public override bool Equals(object obj)
656656
{
657-
TextInfo that = obj as TextInfo;
658-
659-
if (that != null)
657+
if (obj is TextInfo that)
660658
{
661659
return CultureName.Equals(that.CultureName);
662660
}

src/System.Private.CoreLib/shared/System/IO/FileStreamCompletionSource.Win32.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,8 +137,7 @@ internal static unsafe void IOCallback(uint errorCode, uint numBytes, NativeOver
137137
// be directly the FileStreamCompletion that's completing (in the case where the preallocated
138138
// overlapped was already in use by another operation).
139139
object state = ThreadPoolBoundHandle.GetNativeOverlappedState(pOverlapped);
140-
FileStream fs = state as FileStream;
141-
FileStreamCompletionSource completionSource = fs != null ?
140+
FileStreamCompletionSource completionSource = state is FileStream fs ?
142141
fs._currentOverlappedOwner :
143142
(FileStreamCompletionSource)state;
144143
Debug.Assert(completionSource._overlapped == pOverlapped, "Overlaps don't match");

src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -527,8 +527,7 @@ public override Task CopyToAsync(Stream destination, int bufferSize, Cancellatio
527527
return Task.CompletedTask;
528528

529529
// If destination is not a memory stream, write there asynchronously:
530-
MemoryStream memStrDest = destination as MemoryStream;
531-
if (memStrDest == null)
530+
if (!(destination is MemoryStream memStrDest))
532531
return destination.WriteAsync(_buffer, pos, n, cancellationToken);
533532

534533
try

src/System.Private.CoreLib/shared/System/IO/Stream.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1078,8 +1078,7 @@ internal void ThrowIfError()
10781078

10791079
internal static int EndRead(IAsyncResult asyncResult)
10801080
{
1081-
SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult;
1082-
if (ar == null || ar._isWrite)
1081+
if (!(asyncResult is SynchronousAsyncResult ar) || ar._isWrite)
10831082
throw new ArgumentException(SR.Arg_WrongAsyncResult);
10841083

10851084
if (ar._endXxxCalled)
@@ -1093,8 +1092,7 @@ internal static int EndRead(IAsyncResult asyncResult)
10931092

10941093
internal static void EndWrite(IAsyncResult asyncResult)
10951094
{
1096-
SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult;
1097-
if (ar == null || !ar._isWrite)
1095+
if (!(asyncResult is SynchronousAsyncResult ar) || !ar._isWrite)
10981096
throw new ArgumentException(SR.Arg_WrongAsyncResult);
10991097

11001098
if (ar._endXxxCalled)

src/System.Private.CoreLib/shared/System/IO/TextWriter.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -286,8 +286,7 @@ public virtual void Write(object value)
286286
{
287287
if (value != null)
288288
{
289-
IFormattable f = value as IFormattable;
290-
if (f != null)
289+
if (value is IFormattable f)
291290
{
292291
Write(f.ToString(null, FormatProvider));
293292
}
@@ -497,8 +496,7 @@ public virtual void WriteLine(object value)
497496
{
498497
// Call WriteLine(value.ToString), not Write(Object), WriteLine().
499498
// This makes calls to WriteLine(Object) atomic.
500-
IFormattable f = value as IFormattable;
501-
if (f != null)
499+
if (value is IFormattable f)
502500
{
503501
WriteLine(f.ToString(null, FormatProvider));
504502
}

src/System.Private.CoreLib/shared/System/String.Comparison.cs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -511,9 +511,7 @@ public int CompareTo(object value)
511511
return 1;
512512
}
513513

514-
string other = value as string;
515-
516-
if (other == null)
514+
if (!(value is string other))
517515
{
518516
throw new ArgumentException(SR.Arg_MustBeString);
519517
}
@@ -606,8 +604,7 @@ public override bool Equals(object obj)
606604
if (object.ReferenceEquals(this, obj))
607605
return true;
608606

609-
string str = obj as string;
610-
if (str == null)
607+
if (!(obj is string str))
611608
return false;
612609

613610
if (this.Length != str.Length)

0 commit comments

Comments
 (0)