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);
}
}
}
- 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;
}
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);
return _comparer.Compare(a, b);
}
- IComparable ia = a as IComparable;
- if (ia != null)
+ if (a is IComparable ia)
{
return ia.CompareTo(b);
}
// 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)
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;
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
- T[] tArray = array as T[];
- if (tArray != null)
+ if (array is T[] tArray)
{
items.CopyTo(tArray, index);
}
// 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;
}
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
- T[] items = array as T[];
- if (items != null)
+ if (array is T[] items)
{
list.CopyTo(items, index);
}
return true;
}
- DefaultValueAttribute other = obj as DefaultValueAttribute;
-
- if (other != null)
+ if (obj is DefaultValueAttribute other)
{
if (Value != null)
{
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()
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();
}
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
return null;
}
- IConvertible v = value as IConvertible;
- if (v == null)
+ if (!(value is IConvertible v))
{
throw new InvalidCastException(SR.InvalidCast_IConvertible);
}
return null;
}
- IConvertible ic = value as IConvertible;
- if (ic == null)
+ if (!(value is IConvertible ic))
{
if (value.GetType() == conversionType)
{
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();
}
{
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);
}
}
// 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)
{
{
foreach (var esRef in s_EventSources)
{
- EventSource es = esRef.Target as EventSource;
- if (es != null)
+ if (esRef.Target is EventSource es)
es.Dispose();
}
}
// 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)
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.");
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;
public override bool Equals(object value)
{
- CompareInfo that = value as CompareInfo;
-
- if (that != null)
+ if (value is CompareInfo that)
{
return this.Name == that.Name;
}
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)
public override bool Equals(object obj)
{
- IdnMapping that = obj as IdnMapping;
return
- that != null &&
+ obj is IdnMapping that &&
_allowUnassigned == that._allowUnassigned &&
_useStd3AsciiRules == that._useStd3AsciiRules;
}
////////////////////////////////////////////////////////////////////////
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);
}
////////////////////////////////////////////////////////////////////////
public override bool Equals(object value)
{
- SortKey that = value as SortKey;
-
- if (that != null)
+ if (value is SortKey that)
{
return Compare(this, that) == 0;
}
public override bool Equals(object value)
{
- StringInfo that = value as StringInfo;
- if (that != null)
+ if (value is StringInfo that)
{
return (_str.Equals(that._str));
}
////////////////////////////////////////////////////////////////////////
public override bool Equals(object obj)
{
- TextInfo that = obj as TextInfo;
-
- if (that != null)
+ if (obj is TextInfo that)
{
return CultureName.Equals(that.CultureName);
}
// 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");
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
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)
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)
{
if (value != null)
{
- IFormattable f = value as IFormattable;
- if (f != null)
+ if (value is IFormattable f)
{
Write(f.ToString(null, FormatProvider));
}
{
// 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));
}
return 1;
}
- string other = value as string;
-
- if (other == null)
+ if (!(value is string other))
{
throw new ArgumentException(SR.Arg_MustBeString);
}
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)
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);
}
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);
}
throw new ArgumentNullException(nameof(obj));
}
- string s = obj as string;
- if (s != null)
+ if (obj is string s)
{
return GetHashCode(s);
}
// 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);
}
// 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;
}
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);
}
public override bool Equals(object value)
{
- DecoderExceptionFallback that = value as DecoderExceptionFallback;
- if (that != null)
+ if (value is DecoderExceptionFallback that)
{
return (true);
}
public override bool Equals(object value)
{
- DecoderReplacementFallback that = value as DecoderReplacementFallback;
- if (that != null)
+ if (value is DecoderReplacementFallback that)
{
return (_strDefault == that._strDefault);
}
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);
}
public override bool Equals(object value)
{
- EncoderExceptionFallback that = value as EncoderExceptionFallback;
- if (that != null)
+ if (value is EncoderExceptionFallback that)
{
return (true);
}
public override bool Equals(object value)
{
- EncoderReplacementFallback that = value as EncoderReplacementFallback;
- if (that != null)
+ if (value is EncoderReplacementFallback that)
{
return (_strDefault == that._strDefault);
}
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));
public override bool Equals(object value)
{
- EncodingInfo that = value as EncodingInfo;
- if (that != null)
+ if (value is EncodingInfo that)
{
return this.CodePage == that.CodePage;
}
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) &&
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)) &&
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)) &&
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),
{
// 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;
// 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);
}
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;
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
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();
}
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;
{
if (other == null) return false;
- Tuple<T1> objTuple = other as Tuple<T1>;
-
- if (objTuple == null)
+ if (!(other is Tuple<T1> objTuple))
{
return false;
}
{
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));
}
{
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;
}
{
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));
}
{
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;
}
{
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));
}
{
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;
}
{
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));
}
{
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;
}
{
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));
}
{
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;
}
{
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));
}
{
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;
}
{
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));
}
{
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;
}
{
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));
}
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;
}
int lo = index;
int hi = index + length - 1;
- object[] objArray = array as object[];
- if (objArray != null)
+ if (array is object[] objArray)
{
while (lo <= hi)
{
if (r)
return;
- object[] objArray = array as object[];
- if (objArray != null)
+ if (array is object[] objArray)
{
Array.Reverse<object>(objArray, index, length);
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
- IDictionary d = m_dictionary as IDictionary;
- if (d != null)
+ if (m_dictionary is IDictionary d)
{
return d.GetEnumerator();
}
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)
{
{
if (m_syncRoot == null)
{
- ICollection c = m_dictionary as ICollection;
- if (c != null)
+ if (m_dictionary is ICollection c)
{
m_syncRoot = c.SyncRoot;
}
{
if (m_syncRoot == null)
{
- ICollection c = m_collection as ICollection;
- if (c != null)
+ if (m_collection is ICollection c)
{
m_syncRoot = c.SyncRoot;
}
{
if (m_syncRoot == null)
{
- ICollection c = m_collection as ICollection;
- if (c != null)
+ if (m_collection is ICollection c)
{
m_syncRoot = c.SyncRoot;
}
}
// 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);
}
// 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();
}
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
TypeCode typeCode = GetTypeCodeExtended(ParameterType);
if(typeCode == TypeCode.Object)
{
- InvokeTypeInfo typeInfo = TypeInfo as InvokeTypeInfo;
- if(typeInfo == null)
+ if(!(TypeInfo is InvokeTypeInfo typeInfo))
{
throw new NotSupportedException();
}
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
{
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"];
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];
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))
}
else
{
- object[] invocationList = _invocationList as object[];
- if (invocationList != null)
+ if (_invocationList is object[] invocationList)
{
int invocationCount = (int)_invocationCount;
int vInvocationCount = (int)v._invocationCount;
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;
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();
}
}
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();
}
}
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;
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)
{
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);
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;
}
}
- UnmanagedMemoryStream stream = value as UnmanagedMemoryStream;
- if (stream != null && wrapUnmanagedMemStream)
+ if (value is UnmanagedMemoryStream stream && wrapUnmanagedMemStream)
return new UnmanagedMemoryStreamWrapper(stream);
else
return value;
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();
}
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);
}
// 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);
}
// 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))
{
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);
}
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();
}
// 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);
}
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
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
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);
//
// 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
// 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);
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);
// 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);
}
{
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;
{
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);
}
{
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();
}
{
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);
{
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);
}
{
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;
{
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();
}
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();
}
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;
{
// 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;
{
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().
// 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.
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];
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];
{
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();
//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)
// 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;
}
// 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;
// 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;
// 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;
// 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;
// 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)
{