From 9c62a5046b829a7d803226212f63a13b5968f53f Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Fri, 9 Aug 2019 11:32:32 -0400 Subject: [PATCH 1/6] Contribute to IDE0044 (make field readonly) I used the auto-fix and then undid changes in areas where the fields were potentially mutated in native, e.g. I undid many of the changes in reflection. We can revisit those individually later. --- .../shared/Internal/Win32/RegistryKey.cs | 2 +- .../shared/System/AggregateException.cs | 2 +- .../shared/System/ArgumentException.cs | 2 +- .../System/ArgumentOutOfRangeException.cs | 2 +- .../shared/System/Array.Enumerators.cs | 10 +++--- .../shared/System/AttributeUsageAttribute.cs | 2 +- .../shared/System/BadImageFormatException.cs | 4 +-- .../shared/System/CLSCompliantAttribute.cs | 2 +- .../shared/System/Collections/ArrayList.cs | 34 +++++++++---------- .../shared/System/Collections/Comparer.cs | 2 +- .../System/Collections/Generic/Dictionary.cs | 4 +-- .../shared/System/Collections/Hashtable.cs | 12 +++---- .../Collections/ListDictionaryInternal.cs | 14 ++++---- .../Collections/ObjectModel/Collection.cs | 2 +- .../ObjectModel/ReadOnlyCollection.cs | 2 +- .../shared/System/CurrentSystemTimeZone.cs | 6 ++-- .../Contracts/ContractFailedEventArgs.cs | 8 ++--- .../System/Diagnostics/Contracts/Contracts.cs | 16 ++++----- .../shared/System/Diagnostics/StackFrame.cs | 2 +- .../Diagnostics/Tracing/ActivityTracker.cs | 2 +- .../Diagnostics/Tracing/EventDescriptor.cs | 16 ++++----- .../System/Diagnostics/Tracing/EventSource.cs | 29 ++++++++-------- .../Tracing/IncrementingPollingCounter.cs | 2 +- .../Diagnostics/Tracing/PollingCounter.cs | 2 +- .../Diagnostics/Tracing/StubEnvironment.cs | 2 +- .../Tracing/TraceLogging/EventPayload.cs | 4 +-- .../Tracing/TraceLogging/SimpleTypeInfos.cs | 10 +++--- .../Globalization/CultureNotFoundException.cs | 4 +-- .../Globalization/DateTimeFormatInfo.cs | 2 +- .../System/Globalization/DateTimeParse.cs | 7 ++-- .../System/Globalization/HebrewNumber.cs | 2 +- .../shared/System/Globalization/IdnMapping.cs | 2 +- .../System/Globalization/SortVersion.cs | 2 +- .../System/Globalization/TaiwanCalendar.cs | 2 +- .../System/Globalization/TimeSpanParse.cs | 2 +- .../shared/System/IO/BinaryReader.cs | 8 ++--- .../shared/System/IO/BinaryWriter.cs | 2 +- .../shared/System/IO/MemoryStream.cs | 4 +-- .../System/IO/PinnedBufferMemoryStream.cs | 2 +- .../shared/System/IO/Stream.cs | 6 ++-- .../shared/System/IO/StreamReader.cs | 2 +- .../shared/System/IO/TextWriter.cs | 2 +- .../System/IO/UnmanagedMemoryStreamWrapper.cs | 2 +- .../shared/System/Math.cs | 2 +- .../shared/System/MathF.cs | 2 +- .../shared/System/NotFiniteNumberException.cs | 2 +- .../Number.NumberToFloatingPointBits.cs | 4 +-- .../shared/System/ObjectDisposedException.cs | 2 +- .../shared/System/ObsoleteAttribute.cs | 4 +-- .../shared/System/Random.cs | 2 +- .../Reflection/AssemblyFlagsAttribute.cs | 2 +- .../Resources/FileBasedResourceGroveler.cs | 2 +- .../ManifestBasedResourceGroveler.cs | 2 +- .../MissingSatelliteAssemblyException.cs | 2 +- .../Resources/ResourceFallbackManager.cs | 6 ++-- .../System/Resources/ResourceManager.cs | 8 ++--- .../shared/System/Resources/ResourceReader.cs | 2 +- .../DateTimeConstantAttribute.cs | 2 +- .../DecimalConstantAttribute.cs | 2 +- .../InteropServices/ArrayWithOffset.cs | 6 ++-- .../shared/System/Runtime/MemoryFailPoint.cs | 22 ++++++------ .../System/Runtime/Remoting/ObjectHandle.cs | 2 +- .../Serialization/SerializationInfo.cs | 4 +-- .../Versioning/TargetFrameworkAttribute.cs | 2 +- .../shared/System/StringComparer.cs | 2 +- .../System/Text/DecoderBestFitFallback.cs | 2 +- .../System/Text/DecoderExceptionFallback.cs | 4 +-- .../shared/System/Text/DecoderNLS.cs | 2 +- .../System/Text/DecoderReplacementFallback.cs | 4 +-- .../System/Text/EncoderBestFitFallback.cs | 2 +- .../System/Text/EncoderExceptionFallback.cs | 8 ++--- .../shared/System/Text/EncoderNLS.cs | 2 +- .../System/Text/EncoderReplacementFallback.cs | 4 +-- .../shared/System/Text/Encoding.cs | 30 ++++++++-------- .../shared/System/Text/EncodingProvider.cs | 2 +- .../shared/System/Text/UTF7Encoding.cs | 2 +- .../System/Threading/ReaderWriterLockSlim.cs | 6 ++-- .../shared/System/Threading/Tasks/Future.cs | 2 +- .../System/Threading/Tasks/FutureFactory.cs | 8 ++--- .../shared/System/Threading/Tasks/Task.cs | 2 +- .../System/Threading/Tasks/TaskScheduler.cs | 4 +-- .../shared/System/Threading/ThreadLocal.cs | 4 +-- .../shared/System/Threading/ThreadPool.cs | 10 +++--- .../shared/System/Threading/Timer.cs | 2 +- .../System/TypeInitializationException.cs | 2 +- .../System/UnhandledExceptionEventArgs.cs | 4 +-- .../Runtime/InteropServices/ComActivator.cs | 16 ++++----- .../ObjectModel/ReadOnlyDictionary.cs | 2 +- .../System/Diagnostics/Eventing/EventPipe.cs | 14 ++++---- .../Eventing/EventPipeEventDispatcher.cs | 10 +++--- .../src/System/Exception.CoreCLR.cs | 10 +++--- .../TypeDependencyAttribute.cs | 2 +- .../Runtime/InteropServices/ComEventsInfo.cs | 2 +- .../InteropServices/ComEventsMethod.cs | 2 +- .../EnumeratorViewOfEnumVariant.cs | 2 +- .../WindowsRuntime/Attributes.cs | 14 ++++---- .../WindowsRuntime/CLRIPropertyValueImpl.cs | 4 +-- .../WindowsRuntime/CLRIReferenceImpl.cs | 6 ++-- .../WindowsRuntime/ConstantSplittableMap.cs | 6 ++-- .../WindowsRuntime/CustomPropertyImpl.cs | 2 +- .../EnumeratorToIteratorAdapter.cs | 4 +-- .../EventRegistrationTokenTable.cs | 2 +- .../WindowsRuntime/ICustomPropertyProvider.cs | 8 ++--- .../IteratorToEnumeratorAdapter.cs | 4 +-- .../ManagedActivationFactory.cs | 2 +- .../WindowsRuntime/WindowsRuntimeMarshal.cs | 6 ++-- .../WindowsRuntime/WindowsRuntimeMetadata.cs | 6 ++-- .../src/System/RuntimeType.CoreCLR.cs | 10 +++--- .../src/System/Threading/Overlapped.cs | 6 ++-- .../Threading/Tasks/AsyncCausalityTracer.cs | 2 +- .../src/System/TypeNameParser.cs | 2 +- 111 files changed, 290 insertions(+), 290 deletions(-) diff --git a/src/System.Private.CoreLib/shared/Internal/Win32/RegistryKey.cs b/src/System.Private.CoreLib/shared/Internal/Win32/RegistryKey.cs index 013b442b6f4a..90ffabb0e7ac 100644 --- a/src/System.Private.CoreLib/shared/Internal/Win32/RegistryKey.cs +++ b/src/System.Private.CoreLib/shared/Internal/Win32/RegistryKey.cs @@ -29,7 +29,7 @@ internal sealed class RegistryKey : IDisposable private const int MaxKeyLength = 255; private const int MaxValueLength = 16383; - private SafeRegistryHandle _hkey; + private readonly SafeRegistryHandle _hkey; private RegistryKey(SafeRegistryHandle hkey) { diff --git a/src/System.Private.CoreLib/shared/System/AggregateException.cs b/src/System.Private.CoreLib/shared/System/AggregateException.cs index 49809b104814..e0f079fe2390 100644 --- a/src/System.Private.CoreLib/shared/System/AggregateException.cs +++ b/src/System.Private.CoreLib/shared/System/AggregateException.cs @@ -25,7 +25,7 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class AggregateException : Exception { - private ReadOnlyCollection m_innerExceptions; // Complete set of exceptions. Do not rename (binary serialization) + private readonly ReadOnlyCollection m_innerExceptions; // Complete set of exceptions. Do not rename (binary serialization) /// /// Initializes a new instance of the class. diff --git a/src/System.Private.CoreLib/shared/System/ArgumentException.cs b/src/System.Private.CoreLib/shared/System/ArgumentException.cs index 2fd3c880ecee..41711870ade0 100644 --- a/src/System.Private.CoreLib/shared/System/ArgumentException.cs +++ b/src/System.Private.CoreLib/shared/System/ArgumentException.cs @@ -23,7 +23,7 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ArgumentException : SystemException { - private string? _paramName; + private readonly string? _paramName; // Creates a new ArgumentException with its message // string set to the empty string. diff --git a/src/System.Private.CoreLib/shared/System/ArgumentOutOfRangeException.cs b/src/System.Private.CoreLib/shared/System/ArgumentOutOfRangeException.cs index 0ffc4e4aee71..3b9ae7e8e90d 100644 --- a/src/System.Private.CoreLib/shared/System/ArgumentOutOfRangeException.cs +++ b/src/System.Private.CoreLib/shared/System/ArgumentOutOfRangeException.cs @@ -22,7 +22,7 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ArgumentOutOfRangeException : ArgumentException { - private object? _actualValue; + private readonly object? _actualValue; // Creates a new ArgumentOutOfRangeException with its message // string set to a default message explaining an argument was out of range. diff --git a/src/System.Private.CoreLib/shared/System/Array.Enumerators.cs b/src/System.Private.CoreLib/shared/System/Array.Enumerators.cs index 74349ab23809..8029ab218d4c 100644 --- a/src/System.Private.CoreLib/shared/System/Array.Enumerators.cs +++ b/src/System.Private.CoreLib/shared/System/Array.Enumerators.cs @@ -10,11 +10,11 @@ namespace System { internal sealed class ArrayEnumerator : IEnumerator, ICloneable { - private Array array; + private readonly Array array; private int index; - private int endIndex; - private int startIndex; // Save for Reset. - private int[] _indices; // The current position in a multidim array + private readonly int endIndex; + private readonly int startIndex; // Save for Reset. + private readonly int[] _indices; // The current position in a multidim array private bool _complete; internal ArrayEnumerator(Array array, int index, int count) @@ -110,7 +110,7 @@ internal sealed class SZArrayEnumerator : IEnumerator, ICloneable { private readonly Array _array; private int _index; - private int _endIndex; // Cache Array.Length, since it's a little slow. + private readonly int _endIndex; // Cache Array.Length, since it's a little slow. internal SZArrayEnumerator(Array array) { diff --git a/src/System.Private.CoreLib/shared/System/AttributeUsageAttribute.cs b/src/System.Private.CoreLib/shared/System/AttributeUsageAttribute.cs index 06fb7f9a5060..978910b943d3 100644 --- a/src/System.Private.CoreLib/shared/System/AttributeUsageAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/AttributeUsageAttribute.cs @@ -19,7 +19,7 @@ namespace System [AttributeUsage(AttributeTargets.Class, Inherited = true)] public sealed class AttributeUsageAttribute : Attribute { - private AttributeTargets _attributeTarget = AttributeTargets.All; // Defaults to all + private readonly AttributeTargets _attributeTarget = AttributeTargets.All; // Defaults to all private bool _allowMultiple = false; // Defaults to false private bool _inherited = true; // Defaults to true diff --git a/src/System.Private.CoreLib/shared/System/BadImageFormatException.cs b/src/System.Private.CoreLib/shared/System/BadImageFormatException.cs index 5d065e7bba27..aa39a9a95ad7 100644 --- a/src/System.Private.CoreLib/shared/System/BadImageFormatException.cs +++ b/src/System.Private.CoreLib/shared/System/BadImageFormatException.cs @@ -21,8 +21,8 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public partial class BadImageFormatException : SystemException { - private string? _fileName; // The name of the corrupt PE file. - private string? _fusionLog; // fusion log (when applicable) + private readonly string? _fileName; // The name of the corrupt PE file. + private readonly string? _fusionLog; // fusion log (when applicable) public BadImageFormatException() : base(SR.Arg_BadImageFormatException) diff --git a/src/System.Private.CoreLib/shared/System/CLSCompliantAttribute.cs b/src/System.Private.CoreLib/shared/System/CLSCompliantAttribute.cs index d895b5ac7166..9de638ee8de2 100644 --- a/src/System.Private.CoreLib/shared/System/CLSCompliantAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/CLSCompliantAttribute.cs @@ -16,7 +16,7 @@ namespace System [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)] public sealed class CLSCompliantAttribute : Attribute { - private bool _compliant; + private readonly bool _compliant; public CLSCompliantAttribute(bool isCompliant) { diff --git a/src/System.Private.CoreLib/shared/System/Collections/ArrayList.cs b/src/System.Private.CoreLib/shared/System/Collections/ArrayList.cs index 3f1cba08514a..d4ae3da5350d 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/ArrayList.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/ArrayList.cs @@ -772,7 +772,7 @@ public virtual void TrimToSize() // Note this requires reimplementing half of ArrayList... private class IListWrapper : ArrayList { - private IList _list; + private readonly IList _list; internal IListWrapper(IList list) { @@ -1235,8 +1235,8 @@ public void Reset() private class SyncArrayList : ArrayList { - private ArrayList _list; - private object _root; + private readonly ArrayList _list; + private readonly object _root; internal SyncArrayList(ArrayList list) : base(false) @@ -1590,8 +1590,8 @@ public override void TrimToSize() private class SyncIList : IList { - private IList _list; - private object _root; + private readonly IList _list; + private readonly object _root; internal SyncIList(IList list) { @@ -1719,7 +1719,7 @@ public virtual void RemoveAt(int index) private class FixedSizeList : IList { - private IList _list; + private readonly IList _list; internal FixedSizeList(IList l) { @@ -2031,7 +2031,7 @@ public override void TrimToSize() private class ReadOnlyList : IList { - private IList _list; + private readonly IList _list; internal ReadOnlyList(IList l) { @@ -2343,12 +2343,12 @@ public override void TrimToSize() // made to the list while an enumeration is in progress. private sealed class ArrayListEnumerator : IEnumerator, ICloneable { - private ArrayList _list; + private readonly ArrayList _list; private int _index; - private int _endIndex; // Where to stop. - private int _version; + private readonly int _endIndex; // Where to stop. + private readonly int _version; private object? _currentElement; - private int _startIndex; // Save this for Reset. + private readonly int _startIndex; // Save this for Reset. internal ArrayListEnumerator(ArrayList list, int index, int count) { @@ -2404,7 +2404,7 @@ public void Reset() private class Range : ArrayList { private ArrayList _baseList; - private int _baseIndex; + private readonly int _baseIndex; private int _baseSize; private int _baseVersion; @@ -2819,13 +2819,13 @@ public override void TrimToSize() private sealed class ArrayListEnumeratorSimple : IEnumerator, ICloneable { - private ArrayList _list; + private readonly ArrayList _list; private int _index; - private int _version; + private readonly int _version; private object? _currentElement; - private bool _isArrayList; + private readonly bool _isArrayList; // this object is used to indicate enumeration has not started or has terminated - private static object s_dummyObject = new object(); + private static readonly object s_dummyObject = new object(); internal ArrayListEnumeratorSimple(ArrayList list) { @@ -2910,7 +2910,7 @@ public void Reset() internal class ArrayListDebugView { - private ArrayList _arrayList; + private readonly ArrayList _arrayList; public ArrayListDebugView(ArrayList arrayList) { diff --git a/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs b/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs index 7775283367c8..e8f431be6db3 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs @@ -17,7 +17,7 @@ namespace System.Collections [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class Comparer : IComparer, ISerializable { - private CompareInfo _compareInfo; + private readonly CompareInfo _compareInfo; public static readonly Comparer Default = new Comparer(CultureInfo.CurrentCulture); public static readonly Comparer DefaultInvariant = new Comparer(CultureInfo.InvariantCulture); diff --git a/src/System.Private.CoreLib/shared/System/Collections/Generic/Dictionary.cs b/src/System.Private.CoreLib/shared/System/Collections/Generic/Dictionary.cs index 7f14fd7cb90f..1bd9056265ce 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/Generic/Dictionary.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/Generic/Dictionary.cs @@ -1290,7 +1290,7 @@ object IDictionaryEnumerator.Key [DebuggerDisplay("Count = {Count}")] public sealed class KeyCollection : ICollection, ICollection, IReadOnlyCollection { - private Dictionary _dictionary; + private readonly Dictionary _dictionary; public KeyCollection(Dictionary dictionary) { @@ -1473,7 +1473,7 @@ void IEnumerator.Reset() [DebuggerDisplay("Count = {Count}")] public sealed class ValueCollection : ICollection, ICollection, IReadOnlyCollection { - private Dictionary _dictionary; + private readonly Dictionary _dictionary; public ValueCollection(Dictionary dictionary) { diff --git a/src/System.Private.CoreLib/shared/System/Collections/Hashtable.cs b/src/System.Private.CoreLib/shared/System/Collections/Hashtable.cs index 974bdf9bef8a..2b3bb5774913 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/Hashtable.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/Hashtable.cs @@ -1251,7 +1251,7 @@ public virtual void OnDeserialization(object? sender) // class is created by the GetKeys method of a hashtable. private class KeyCollection : ICollection { - private Hashtable _hashtable; + private readonly Hashtable _hashtable; internal KeyCollection(Hashtable hashtable) { @@ -1296,7 +1296,7 @@ public virtual int Count // this class is created by the GetValues method of a hashtable. private class ValueCollection : ICollection { - private Hashtable _hashtable; + private readonly Hashtable _hashtable; internal ValueCollection(Hashtable hashtable) { @@ -1510,11 +1510,11 @@ internal override KeyValuePairs[] ToKeyValuePairsArray() // are made to the hashtable while an enumeration is in progress. private class HashtableEnumerator : IDictionaryEnumerator, ICloneable { - private Hashtable _hashtable; + private readonly Hashtable _hashtable; private int _bucket; - private int _version; + private readonly int _version; private bool _current; - private int _getObjectRetType; // What should GetObject return? + private readonly int _getObjectRetType; // What should GetObject return? private object? _currentKey; private object? _currentValue; @@ -1614,7 +1614,7 @@ public virtual void Reset() // internal debug view class for hashtable internal class HashtableDebugView { - private Hashtable _hashtable; + private readonly Hashtable _hashtable; public HashtableDebugView(Hashtable hashtable) { diff --git a/src/System.Private.CoreLib/shared/System/Collections/ListDictionaryInternal.cs b/src/System.Private.CoreLib/shared/System/Collections/ListDictionaryInternal.cs index 2e23aa5bf73c..0585b08552be 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/ListDictionaryInternal.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/ListDictionaryInternal.cs @@ -269,9 +269,9 @@ public void Remove(object key) private class NodeEnumerator : IDictionaryEnumerator { - private ListDictionaryInternal list; + private readonly ListDictionaryInternal list; private DictionaryNode? current; - private int version; + private readonly int version; private bool start; @@ -362,8 +362,8 @@ public void Reset() private class NodeKeyValueCollection : ICollection { - private ListDictionaryInternal list; - private bool isKeys; + private readonly ListDictionaryInternal list; + private readonly bool isKeys; public NodeKeyValueCollection(ListDictionaryInternal list, bool isKeys) { @@ -425,10 +425,10 @@ IEnumerator IEnumerable.GetEnumerator() private class NodeKeyValueEnumerator : IEnumerator { - private ListDictionaryInternal list; + private readonly ListDictionaryInternal list; private DictionaryNode? current; - private int version; - private bool isKeys; + private readonly int version; + private readonly bool isKeys; private bool start; public NodeKeyValueEnumerator(ListDictionaryInternal list, bool isKeys) diff --git a/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/Collection.cs b/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/Collection.cs index 6dec16fa5780..d87594e5e2a2 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/Collection.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/Collection.cs @@ -13,7 +13,7 @@ namespace System.Collections.ObjectModel [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Collection : IList, IList, IReadOnlyList { - private IList items; // Do not rename (binary serialization) + private readonly IList items; // Do not rename (binary serialization) public Collection() { diff --git a/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs b/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs index b68a03292adc..1f99b892cddd 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs @@ -13,7 +13,7 @@ namespace System.Collections.ObjectModel [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ReadOnlyCollection : IList, IList, IReadOnlyList { - private IList list; // Do not rename (binary serialization) + private readonly IList list; // Do not rename (binary serialization) public ReadOnlyCollection(IList list) { diff --git a/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs b/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs index a3d00c102d04..285dcba29be3 100644 --- a/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs +++ b/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs @@ -29,9 +29,9 @@ internal class CurrentSystemTimeZone : TimeZone // no daylight saving is in used. // E.g. the offset for PST (Pacific Standard time) should be -8 * 60 * 60 * 1000 * 10000. // (1 millisecond = 10000 ticks) - private long m_ticksOffset; - private string m_standardName; - private string m_daylightName; + private readonly long m_ticksOffset; + private readonly string m_standardName; + private readonly string m_daylightName; internal CurrentSystemTimeZone() { diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Contracts/ContractFailedEventArgs.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Contracts/ContractFailedEventArgs.cs index 3c58ca10da5b..b0cd50950ca1 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Contracts/ContractFailedEventArgs.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Contracts/ContractFailedEventArgs.cs @@ -12,10 +12,10 @@ namespace System.Diagnostics.Contracts { public sealed class ContractFailedEventArgs : EventArgs { - private ContractFailureKind _failureKind; - private string? _message; - private string? _condition; - private Exception? _originalException; + private readonly ContractFailureKind _failureKind; + private readonly string? _message; + private readonly string? _condition; + private readonly Exception? _originalException; private bool _handled; private bool _unwind; diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Contracts/Contracts.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Contracts/Contracts.cs index a176746b4d4d..72762e8a71a7 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Contracts/Contracts.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Contracts/Contracts.cs @@ -42,7 +42,7 @@ public sealed class PureAttribute : Attribute [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] public sealed class ContractClassAttribute : Attribute { - private Type _typeWithContracts; + private readonly Type _typeWithContracts; public ContractClassAttribute(Type typeContainingContracts) { @@ -62,7 +62,7 @@ public Type TypeContainingContracts [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class ContractClassForAttribute : Attribute { - private Type _typeIAmAContractFor; + private readonly Type _typeIAmAContractFor; public ContractClassForAttribute(Type typeContractsAreFor) { @@ -121,7 +121,7 @@ public sealed class ContractRuntimeIgnoredAttribute : Attribute [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)] public sealed class ContractVerificationAttribute : Attribute { - private bool _value; + private readonly bool _value; public ContractVerificationAttribute(bool value) { _value = value; } @@ -139,7 +139,7 @@ public bool Value [AttributeUsage(AttributeTargets.Field)] public sealed class ContractPublicPropertyNameAttribute : Attribute { - private string _publicName; + private readonly string _publicName; public ContractPublicPropertyNameAttribute(string name) { @@ -178,10 +178,10 @@ public sealed class ContractAbbreviatorAttribute : Attribute [Conditional("CONTRACTS_FULL")] public sealed class ContractOptionAttribute : Attribute { - private string _category; - private string _setting; - private bool _enabled; - private string? _value; + private readonly string _category; + private readonly string _setting; + private readonly bool _enabled; + private readonly string? _value; public ContractOptionAttribute(string category, string setting, bool enabled) { diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/StackFrame.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/StackFrame.cs index 1683206bbce0..47c82309756d 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/StackFrame.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/StackFrame.cs @@ -47,7 +47,7 @@ public partial class StackFrame /// /// This flag is set to true when the frame represents a rethrow marker. /// - private bool _isLastFrameFromForeignExceptionStackTrace; + private readonly bool _isLastFrameFromForeignExceptionStackTrace; private void InitMembers() { diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/ActivityTracker.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/ActivityTracker.cs index 9647a7aaa3ba..3f2a12dbbfba 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/ActivityTracker.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/ActivityTracker.cs @@ -613,7 +613,7 @@ private void ActivityChanging(AsyncLocalValueChangedArgs args) private bool m_checkedForEnable; // Singleton - private static ActivityTracker s_activityTrackerInstance = new ActivityTracker(); + private static readonly ActivityTracker s_activityTrackerInstance = new ActivityTracker(); // Used to create unique IDs at the top level. Not used for nested Ids (each activity has its own id generator) private static long m_nextId = 0; diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventDescriptor.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventDescriptor.cs index 770ea4a2f5b9..1646a37fd372 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventDescriptor.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventDescriptor.cs @@ -43,21 +43,21 @@ struct EventDescriptor { #region private [FieldOffset(0)] - private int m_traceloggingId; + private readonly int m_traceloggingId; [FieldOffset(0)] - private ushort m_id; + private readonly ushort m_id; [FieldOffset(2)] - private byte m_version; + private readonly byte m_version; [FieldOffset(3)] - private byte m_channel; + private readonly byte m_channel; [FieldOffset(4)] - private byte m_level; + private readonly byte m_level; [FieldOffset(5)] - private byte m_opcode; + private readonly byte m_opcode; [FieldOffset(6)] - private ushort m_task; + private readonly ushort m_task; [FieldOffset(8)] - private long m_keywords; + private readonly long m_keywords; #endregion public EventDescriptor( diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs index f7669b1a3b9d..771b5f1ff749 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs @@ -2431,8 +2431,8 @@ protected override void OnControllerCommand(ControllerCommand command, IDictiona m_eventSource.SendCommand(listener, m_eventProviderType, perEventSourceSessionId, etwSessionId, (EventCommand)command, IsEnabled(), Level, MatchAnyKeyword, arguments); } - private EventSource m_eventSource; - private EventProviderType m_eventProviderType; + private readonly EventSource m_eventSource; + private readonly EventProviderType m_eventProviderType; } #endif @@ -3913,7 +3913,7 @@ private bool SelfDescribingEvents private EventHandler? m_eventCommandExecuted; - private EventSourceSettings m_config; // configuration information + private readonly EventSourceSettings m_config; // configuration information private bool m_eventSourceDisposed; // has Dispose been called. @@ -4962,7 +4962,7 @@ internal EventWrittenEventArgs(EventSource eventSource) } private string? m_message; private string? m_eventName; - private EventSource m_eventSource; + private readonly EventSource m_eventSource; private ReadOnlyCollection? m_payloadNames; private Guid m_activityId; private long? m_osThreadId; @@ -6280,15 +6280,14 @@ private class ChannelInfo } #endif - private Dictionary opcodeTab; + private readonly Dictionary opcodeTab; private Dictionary? taskTab; #if FEATURE_MANAGED_ETW_CHANNELS private Dictionary? channelTab; #endif private Dictionary? keywordTab; private Dictionary? mapsTab; - - private Dictionary stringTab; // Maps unlocalized strings to localized ones + private readonly Dictionary stringTab; // Maps unlocalized strings to localized ones #if FEATURE_MANAGED_ETW_CHANNELS // WCF used EventSource to mimic a existing ETW manifest. To support this @@ -6301,17 +6300,17 @@ private class ChannelInfo private const int MaxCountChannels = 8; // a manifest can defined at most 8 ETW channels #endif - private StringBuilder sb; // Holds the provider information. - private StringBuilder events; // Holds the events. - private StringBuilder templates; + private readonly StringBuilder sb; // Holds the provider information. + private readonly StringBuilder events; // Holds the events. + private readonly StringBuilder templates; #if FEATURE_MANAGED_ETW_CHANNELS - private string providerName; + private readonly string providerName; #endif - private ResourceManager? resources; // Look up localized strings here. - private EventManifestOptions flags; - private IList errors; // list of currently encountered errors - private Dictionary> perEventByteArrayArgIndices; // "event_name" -> List_of_Indices_of_Byte[]_Arg + private readonly ResourceManager? resources; // Look up localized strings here. + private readonly EventManifestOptions flags; + private readonly IList errors; // list of currently encountered errors + private readonly Dictionary> perEventByteArrayArgIndices; // "event_name" -> List_of_Indices_of_Byte[]_Arg // State we track between StartEvent and EndEvent. private string? eventName; // Name of the event currently being processed. diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/IncrementingPollingCounter.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/IncrementingPollingCounter.cs index 364f4d5ec270..4050daf38cb0 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/IncrementingPollingCounter.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/IncrementingPollingCounter.cs @@ -47,7 +47,7 @@ public IncrementingPollingCounter(string name, EventSource eventSource, Func _totalValueProvider; + private readonly Func _totalValueProvider; /// /// Calls "_totalValueProvider" to enqueue the counter value to the queue. diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/PollingCounter.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/PollingCounter.cs index 2b94119fb5ee..3238fcf03579 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/PollingCounter.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/PollingCounter.cs @@ -42,7 +42,7 @@ public PollingCounter(string name, EventSource eventSource, Func metricP public override string ToString() => $"PollingCounter '{Name}' Count {1} Mean {_lastVal.ToString("n3")}"; - private Func _metricProvider; + private readonly Func _metricProvider; private double _lastVal; internal override void WritePayload(float intervalSec, int pollingIntervalMillisec) diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/StubEnvironment.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/StubEnvironment.cs index 2bd5de50496c..7dcfbf1876f2 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/StubEnvironment.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/StubEnvironment.cs @@ -44,7 +44,7 @@ public static string GetRuntimeResourceString(string key, params object?[] args) return GetResourceString(key, args); } - private static System.Resources.ResourceManager rm = new System.Resources.ResourceManager("Microsoft.Diagnostics.Tracing.Messages", typeof(Environment).Assembly()); + private static readonly System.Resources.ResourceManager rm = new System.Resources.ResourceManager("Microsoft.Diagnostics.Tracing.Messages", typeof(Environment).Assembly()); } #if ES_BUILD_STANDALONE diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs index ff5a048d94e5..a32770894e9a 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs @@ -150,8 +150,8 @@ public bool TryGetValue(string key, [MaybeNullWhen(false)] out object? value) } #region private - private List m_names; - private List m_values; + private readonly List m_names; + private readonly List m_values; #endregion } } diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs index 466ad010021b..64579d119ad2 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs @@ -50,8 +50,8 @@ public override void WriteData(TraceLoggingDataCollector collector, PropertyValu /// internal sealed class ScalarTypeInfo : TraceLoggingTypeInfo { - private Func formatFunc; - private TraceLoggingDataType nativeFormat; + private readonly Func formatFunc; + private readonly TraceLoggingDataType nativeFormat; private ScalarTypeInfo( Type type, @@ -96,9 +96,9 @@ public override void WriteData(TraceLoggingDataCollector collector, PropertyValu /// internal sealed class ScalarArrayTypeInfo : TraceLoggingTypeInfo { - private Func formatFunc; - private TraceLoggingDataType nativeFormat; - private int elementSize; + private readonly Func formatFunc; + private readonly TraceLoggingDataType nativeFormat; + private readonly int elementSize; private ScalarArrayTypeInfo( Type type, diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CultureNotFoundException.cs b/src/System.Private.CoreLib/shared/System/Globalization/CultureNotFoundException.cs index e17385564b5c..c053ec44a540 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CultureNotFoundException.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CultureNotFoundException.cs @@ -10,8 +10,8 @@ namespace System.Globalization [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class CultureNotFoundException : ArgumentException { - private string? _invalidCultureName; // unrecognized culture name - private int? _invalidCultureId; // unrecognized culture Lcid + private readonly string? _invalidCultureName; // unrecognized culture name + private readonly int? _invalidCultureId; // unrecognized culture Lcid public CultureNotFoundException() : base(DefaultMessage) diff --git a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs index a0afc8f76c0b..67a7b47c5e89 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs @@ -54,7 +54,7 @@ public sealed class DateTimeFormatInfo : IFormatProvider, ICloneable private static volatile DateTimeFormatInfo? s_invariantInfo; // an index which points to a record in Culture Data Table. - private CultureData _cultureData; + private readonly CultureData _cultureData; // The culture name used to create this DTFI. private string? _name = null; diff --git a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs index 511a440588c0..8008f328f3c9 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs @@ -332,7 +332,7 @@ internal enum DS //////////////////////////////////////////////////////////////////////////// // End NumEnd NumAmPm NumSpace NumDaySep NumTimesep MonthEnd MonthSpace MonthDSep NumDateSuff NumTimeSuff DayOfWeek YearSpace YearDateSep YearEnd TimeZone Era UTCTimeMark - private static DS[][] dateParsingStates = { + private static readonly DS[][] dateParsingStates = { // DS.BEGIN // DS.BEGIN new DS[] { DS.BEGIN, DS.ERROR, DS.TX_N, DS.N, DS.D_Nd, DS.T_Nt, DS.ERROR, DS.D_M, DS.D_M, DS.D_S, DS.T_S, DS.BEGIN, DS.D_Y, DS.D_Y, DS.ERROR, DS.BEGIN, DS.BEGIN, DS.ERROR}, @@ -5246,6 +5246,7 @@ private static void Trace(string s) // Internal.Console.WriteLine(s); } + // for testing; do not make this readonly private static bool _tracingEnabled = false; #endif // _LOGGING } @@ -5274,10 +5275,10 @@ internal ref struct __DTString // The current character to be looked at. internal char m_current; - private CompareInfo m_info; + private readonly CompareInfo m_info; // Flag to indicate if we encouter an digit, we should check for token or not. // In some cultures, such as mn-MN, it uses "\x0031\x00a0\x0434\x04af\x0433\x044d\x044d\x0440\x00a0\x0441\x0430\x0440" in month names. - private bool m_checkDigitToken; + private readonly bool m_checkDigitToken; internal __DTString(ReadOnlySpan str, DateTimeFormatInfo dtfi, bool checkDigitToken) : this(str, dtfi) { diff --git a/src/System.Private.CoreLib/shared/System/Globalization/HebrewNumber.cs b/src/System.Private.CoreLib/shared/System/Globalization/HebrewNumber.cs index a2054377d5dd..2eaf58ac2ab6 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/HebrewNumber.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/HebrewNumber.cs @@ -282,7 +282,7 @@ internal HebrewValue(HebrewToken token, short value) }; private const int minHebrewNumberCh = 0x05d0; - private static char s_maxHebrewNumberCh = (char)(minHebrewNumberCh + s_hebrewValues.Length - 1); + private static readonly char s_maxHebrewNumberCh = (char)(minHebrewNumberCh + s_hebrewValues.Length - 1); //////////////////////////////////////////////////////////////////////////// // diff --git a/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.cs b/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.cs index 5e54571815fe..4925872348e6 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.cs @@ -183,7 +183,7 @@ private static unsafe string GetStringForOutput(string originalString, char* inp // Legal "dot" separators (i.e: . in www.microsoft.com) - private static char[] c_Dots = { '.', '\u3002', '\uFF0E', '\uFF61' }; + private static readonly char[] c_Dots = { '.', '\u3002', '\uFF0E', '\uFF61' }; private string GetAsciiInvariant(string unicode, int index, int count) { diff --git a/src/System.Private.CoreLib/shared/System/Globalization/SortVersion.cs b/src/System.Private.CoreLib/shared/System/Globalization/SortVersion.cs index d99a999cb50e..f2b8e56675e0 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/SortVersion.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/SortVersion.cs @@ -13,7 +13,7 @@ public sealed class SortVersion : IEquatable #nullable restore { - private int m_NlsVersion; // Do not rename (binary serialization) + private readonly int m_NlsVersion; // Do not rename (binary serialization) private Guid m_SortId; // Do not rename (binary serialization) public int FullVersion => m_NlsVersion; diff --git a/src/System.Private.CoreLib/shared/System/Globalization/TaiwanCalendar.cs b/src/System.Private.CoreLib/shared/System/Globalization/TaiwanCalendar.cs index a0f64c9df25a..d9bd22153805 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/TaiwanCalendar.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/TaiwanCalendar.cs @@ -25,7 +25,7 @@ public class TaiwanCalendar : Calendar // When Gregorian Year 1912 is year 1, so that // 1912 = 1 + yearOffset // So yearOffset = 1911 - private static EraInfo[] s_taiwanEraInfo = new EraInfo[] + private static readonly EraInfo[] s_taiwanEraInfo = new EraInfo[] { new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear }; diff --git a/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs b/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs index 20669bf13753..7dfac05aaddc 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs @@ -153,7 +153,7 @@ public bool NormalizeAndValidateFraction() private ref struct TimeSpanTokenizer { - private ReadOnlySpan _value; + private readonly ReadOnlySpan _value; private int _pos; internal TimeSpanTokenizer(ReadOnlySpan input) : this(input, 0) { } diff --git a/src/System.Private.CoreLib/shared/System/IO/BinaryReader.cs b/src/System.Private.CoreLib/shared/System/IO/BinaryReader.cs index 3f8055a4ab78..e684940b93a7 100644 --- a/src/System.Private.CoreLib/shared/System/IO/BinaryReader.cs +++ b/src/System.Private.CoreLib/shared/System/IO/BinaryReader.cs @@ -31,12 +31,12 @@ public class BinaryReader : IDisposable private readonly Decoder _decoder; private byte[]? _charBytes; private char[]? _charBuffer; - private int _maxCharsSize; // From MaxCharBytesSize & Encoding + private readonly int _maxCharsSize; // From MaxCharBytesSize & Encoding // Performance optimization for Read() w/ Unicode. Speeds us up by ~40% - private bool _2BytesPerChar; - private bool _isMemoryStream; // "do we sit on MemoryStream?" for Read/ReadInt32 perf - private bool _leaveOpen; + private readonly bool _2BytesPerChar; + private readonly bool _isMemoryStream; // "do we sit on MemoryStream?" for Read/ReadInt32 perf + private readonly bool _leaveOpen; private bool _disposed; public BinaryReader(Stream input) : this(input, Encoding.UTF8, false) diff --git a/src/System.Private.CoreLib/shared/System/IO/BinaryWriter.cs b/src/System.Private.CoreLib/shared/System/IO/BinaryWriter.cs index 1f20a5450f14..f0de8736cfa7 100644 --- a/src/System.Private.CoreLib/shared/System/IO/BinaryWriter.cs +++ b/src/System.Private.CoreLib/shared/System/IO/BinaryWriter.cs @@ -22,7 +22,7 @@ public class BinaryWriter : IDisposable, IAsyncDisposable private readonly Encoding _encoding; private readonly Encoder _encoder; - private bool _leaveOpen; + private readonly bool _leaveOpen; // Perf optimization stuff private byte[]? _largeByteBuffer; // temp space for writing chars. diff --git a/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs b/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs index 038d96fc4f77..28ff0399b47b 100644 --- a/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs +++ b/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs @@ -21,7 +21,7 @@ namespace System.IO public class MemoryStream : Stream { private byte[] _buffer; // Either allocated internally or externally. - private int _origin; // For user-provided arrays, start at this origin + private readonly int _origin; // For user-provided arrays, start at this origin private int _position; // read/write head. private int _length; // Number of bytes within the memory stream private int _capacity; // length of usable portion of buffer for stream @@ -29,7 +29,7 @@ public class MemoryStream : Stream private bool _expandable; // User-provided buffers aren't expandable. private bool _writable; // Can user write to this stream? - private bool _exposable; // Whether the array can be returned to the user. + private readonly bool _exposable; // Whether the array can be returned to the user. private bool _isOpen; // Is this stream open or closed? private Task? _lastReadTask; // The last successful task returned from ReadAsync diff --git a/src/System.Private.CoreLib/shared/System/IO/PinnedBufferMemoryStream.cs b/src/System.Private.CoreLib/shared/System/IO/PinnedBufferMemoryStream.cs index 5e663510cd71..6b60ce76a363 100644 --- a/src/System.Private.CoreLib/shared/System/IO/PinnedBufferMemoryStream.cs +++ b/src/System.Private.CoreLib/shared/System/IO/PinnedBufferMemoryStream.cs @@ -22,7 +22,7 @@ namespace System.IO { internal sealed unsafe class PinnedBufferMemoryStream : UnmanagedMemoryStream { - private byte[] _array; + private readonly byte[] _array; private GCHandle _pinningHandle; internal PinnedBufferMemoryStream(byte[] array) diff --git a/src/System.Private.CoreLib/shared/System/IO/Stream.cs b/src/System.Private.CoreLib/shared/System/IO/Stream.cs index 0db1fc161cf2..6910689ee31b 100644 --- a/src/System.Private.CoreLib/shared/System/IO/Stream.cs +++ b/src/System.Private.CoreLib/shared/System/IO/Stream.cs @@ -1026,10 +1026,10 @@ private sealed class SynchronousAsyncResult : IAsyncResult private readonly object? _stateObject; private readonly bool _isWrite; private ManualResetEvent? _waitHandle; - private ExceptionDispatchInfo? _exceptionInfo; + private readonly ExceptionDispatchInfo? _exceptionInfo; private bool _endXxxCalled; - private int _bytesRead; + private readonly int _bytesRead; internal SynchronousAsyncResult(int bytesRead, object? asyncStateObject) { @@ -1114,7 +1114,7 @@ internal static void EndWrite(IAsyncResult asyncResult) // a lock for every operation making it thread safe. private sealed class SyncStream : Stream, IDisposable { - private Stream _stream; + private readonly Stream _stream; internal SyncStream(Stream stream) { diff --git a/src/System.Private.CoreLib/shared/System/IO/StreamReader.cs b/src/System.Private.CoreLib/shared/System/IO/StreamReader.cs index 6695684871ae..9fcfc80fab7b 100644 --- a/src/System.Private.CoreLib/shared/System/IO/StreamReader.cs +++ b/src/System.Private.CoreLib/shared/System/IO/StreamReader.cs @@ -67,7 +67,7 @@ public class StreamReader : TextReader // The intent of this field is to leave open the underlying stream when // disposing of this StreamReader. A name like _leaveOpen is better, // but this type is serializable, and this field's name was _closable. - private bool _closable; // Whether to close the underlying stream. + private readonly bool _closable; // Whether to close the underlying stream. // We don't guarantee thread safety on StreamReader, but we should at // least prevent users from trying to read anything while an Async diff --git a/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs b/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs index 9dfb1405a943..7a1d707ffd70 100644 --- a/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs +++ b/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs @@ -37,7 +37,7 @@ public abstract partial class TextWriter : MarshalByRefObject, IDisposable, IAsy private string CoreNewLineStr = Environment.NewLine; // Can be null - if so, ask for the Thread's CurrentCulture every time. - private IFormatProvider? _internalFormatProvider; + private readonly IFormatProvider? _internalFormatProvider; protected TextWriter() { diff --git a/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs b/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs index 72dcd15b6fa2..9afb7d3c8779 100644 --- a/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs +++ b/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs @@ -21,7 +21,7 @@ namespace System.IO // UnmanagedMemoryStream from ResourceReader. internal sealed class UnmanagedMemoryStreamWrapper : MemoryStream { - private UnmanagedMemoryStream _unmanagedStream; + private readonly UnmanagedMemoryStream _unmanagedStream; internal UnmanagedMemoryStreamWrapper(UnmanagedMemoryStream stream) { diff --git a/src/System.Private.CoreLib/shared/System/Math.cs b/src/System.Private.CoreLib/shared/System/Math.cs index 18d15653f078..cdb11e6f0088 100644 --- a/src/System.Private.CoreLib/shared/System/Math.cs +++ b/src/System.Private.CoreLib/shared/System/Math.cs @@ -35,7 +35,7 @@ public static partial class Math private const double doubleRoundLimit = 1e16d; // This table is required for the Round function which can specify the number of digits to round to - private static double[] roundPower10Double = new double[] { + private static readonly double[] roundPower10Double = new double[] { 1E0, 1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8, 1E9, 1E10, 1E11, 1E12, 1E13, 1E14, 1E15 }; diff --git a/src/System.Private.CoreLib/shared/System/MathF.cs b/src/System.Private.CoreLib/shared/System/MathF.cs index dfc5b59de41c..382af77a5aa1 100644 --- a/src/System.Private.CoreLib/shared/System/MathF.cs +++ b/src/System.Private.CoreLib/shared/System/MathF.cs @@ -28,7 +28,7 @@ public static partial class MathF private const int maxRoundingDigits = 6; // This table is required for the Round function which can specify the number of digits to round to - private static float[] roundPower10Single = new float[] { + private static readonly float[] roundPower10Single = new float[] { 1e0f, 1e1f, 1e2f, 1e3f, 1e4f, 1e5f, 1e6f }; diff --git a/src/System.Private.CoreLib/shared/System/NotFiniteNumberException.cs b/src/System.Private.CoreLib/shared/System/NotFiniteNumberException.cs index 53a5817a7dc7..471e893f3c2d 100644 --- a/src/System.Private.CoreLib/shared/System/NotFiniteNumberException.cs +++ b/src/System.Private.CoreLib/shared/System/NotFiniteNumberException.cs @@ -10,7 +10,7 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class NotFiniteNumberException : ArithmeticException { - private double _offendingNumber; + private readonly double _offendingNumber; public NotFiniteNumberException() : base(SR.Arg_NotFiniteNumberException) diff --git a/src/System.Private.CoreLib/shared/System/Number.NumberToFloatingPointBits.cs b/src/System.Private.CoreLib/shared/System/Number.NumberToFloatingPointBits.cs index ac4c7727f323..54f081ddf071 100644 --- a/src/System.Private.CoreLib/shared/System/Number.NumberToFloatingPointBits.cs +++ b/src/System.Private.CoreLib/shared/System/Number.NumberToFloatingPointBits.cs @@ -64,7 +64,7 @@ public FloatingPointInfo(ushort denormalMantissaBits, ushort exponentBits, int m } } - private static float[] s_Pow10SingleTable = new float[] + private static readonly float[] s_Pow10SingleTable = new float[] { 1e0f, // 10^0 1e1f, // 10^1 @@ -79,7 +79,7 @@ public FloatingPointInfo(ushort denormalMantissaBits, ushort exponentBits, int m 1e10f, // 10^10 }; - private static double[] s_Pow10DoubleTable = new double[] + private static readonly double[] s_Pow10DoubleTable = new double[] { 1e0, // 10^0 1e1, // 10^1 diff --git a/src/System.Private.CoreLib/shared/System/ObjectDisposedException.cs b/src/System.Private.CoreLib/shared/System/ObjectDisposedException.cs index f2bd7e7028f4..a80522af297f 100644 --- a/src/System.Private.CoreLib/shared/System/ObjectDisposedException.cs +++ b/src/System.Private.CoreLib/shared/System/ObjectDisposedException.cs @@ -15,7 +15,7 @@ namespace System [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ObjectDisposedException : InvalidOperationException { - private string? _objectName; + private readonly string? _objectName; // This constructor should only be called by the EE (COMPlusThrow) private ObjectDisposedException() : diff --git a/src/System.Private.CoreLib/shared/System/ObsoleteAttribute.cs b/src/System.Private.CoreLib/shared/System/ObsoleteAttribute.cs index ad6c4eb028b7..b195bb898b11 100644 --- a/src/System.Private.CoreLib/shared/System/ObsoleteAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/ObsoleteAttribute.cs @@ -24,8 +24,8 @@ namespace System Inherited = false)] public sealed class ObsoleteAttribute : Attribute { - private string? _message; - private bool _error; + private readonly string? _message; + private readonly bool _error; public ObsoleteAttribute() { diff --git a/src/System.Private.CoreLib/shared/System/Random.cs b/src/System.Private.CoreLib/shared/System/Random.cs index 06ec46e5240a..2d5ddb0dad2c 100644 --- a/src/System.Private.CoreLib/shared/System/Random.cs +++ b/src/System.Private.CoreLib/shared/System/Random.cs @@ -17,7 +17,7 @@ public class Random // private int _inext; private int _inextp; - private int[] _seedArray = new int[56]; + private readonly int[] _seedArray = new int[56]; // // Public Constants diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyFlagsAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyFlagsAttribute.cs index 1240a669e6fe..df78adb29742 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyFlagsAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyFlagsAttribute.cs @@ -7,7 +7,7 @@ namespace System.Reflection [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyFlagsAttribute : Attribute { - private AssemblyNameFlags _flags; + private readonly AssemblyNameFlags _flags; [Obsolete("This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. https://go.microsoft.com/fwlink/?linkid=14202")] [CLSCompliant(false)] diff --git a/src/System.Private.CoreLib/shared/System/Resources/FileBasedResourceGroveler.cs b/src/System.Private.CoreLib/shared/System/Resources/FileBasedResourceGroveler.cs index 9334e0a2fd85..afcdd293efb8 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/FileBasedResourceGroveler.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/FileBasedResourceGroveler.cs @@ -23,7 +23,7 @@ namespace System.Resources { internal class FileBasedResourceGroveler : IResourceGroveler { - private ResourceManager.ResourceManagerMediator _mediator; + private readonly ResourceManager.ResourceManagerMediator _mediator; public FileBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator) { diff --git a/src/System.Private.CoreLib/shared/System/Resources/ManifestBasedResourceGroveler.cs b/src/System.Private.CoreLib/shared/System/Resources/ManifestBasedResourceGroveler.cs index e23fc138db8d..865d2debb49f 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/ManifestBasedResourceGroveler.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/ManifestBasedResourceGroveler.cs @@ -41,7 +41,7 @@ namespace System.Resources // internal partial class ManifestBasedResourceGroveler : IResourceGroveler { - private ResourceManager.ResourceManagerMediator _mediator; + private readonly ResourceManager.ResourceManagerMediator _mediator; public ManifestBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator) { diff --git a/src/System.Private.CoreLib/shared/System/Resources/MissingSatelliteAssemblyException.cs b/src/System.Private.CoreLib/shared/System/Resources/MissingSatelliteAssemblyException.cs index c092bac47c63..139336270494 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/MissingSatelliteAssemblyException.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/MissingSatelliteAssemblyException.cs @@ -23,7 +23,7 @@ namespace System.Resources [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class MissingSatelliteAssemblyException : SystemException { - private string? _cultureName; + private readonly string? _cultureName; public MissingSatelliteAssemblyException() : base(SR.MissingSatelliteAssembly_Default) diff --git a/src/System.Private.CoreLib/shared/System/Resources/ResourceFallbackManager.cs b/src/System.Private.CoreLib/shared/System/Resources/ResourceFallbackManager.cs index a678e0171e52..70c8d8cc6b62 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/ResourceFallbackManager.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/ResourceFallbackManager.cs @@ -26,9 +26,9 @@ namespace System.Resources { internal class ResourceFallbackManager : IEnumerable { - private CultureInfo m_startingCulture; - private CultureInfo? m_neutralResourcesCulture; - private bool m_useParents; + private readonly CultureInfo m_startingCulture; + private readonly CultureInfo? m_neutralResourcesCulture; + private readonly bool m_useParents; internal ResourceFallbackManager(CultureInfo? startingCulture, CultureInfo? neutralResourcesCulture, bool useParents) { diff --git a/src/System.Private.CoreLib/shared/System/Resources/ResourceManager.cs b/src/System.Private.CoreLib/shared/System/Resources/ResourceManager.cs index a1a8b22afbb2..3a2ea1aee7d8 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/ResourceManager.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/ResourceManager.cs @@ -102,9 +102,9 @@ internal class CultureNameResourceSetPair protected Assembly? MainAssembly; // Need the assembly manifest sometimes. private Dictionary? _resourceSets; - private string? _moduleDir; // For assembly-ignorant directory location - private Type? _locationInfo; // For Assembly or type-based directory layout - private Type? _userResourceSet; // Which ResourceSet instance to create + private readonly string? _moduleDir; // For assembly-ignorant directory location + private readonly Type? _locationInfo; // For Assembly or type-based directory layout + private readonly Type? _userResourceSet; // Which ResourceSet instance to create private CultureInfo? _neutralResourcesCulture; // For perf optimizations. private CultureNameResourceSetPair? _lastUsedResourceCache; @@ -761,7 +761,7 @@ internal static bool IsDefaultType(string asmTypeName, internal class ResourceManagerMediator { - private ResourceManager _rm; + private readonly ResourceManager _rm; internal ResourceManagerMediator(ResourceManager rm) { diff --git a/src/System.Private.CoreLib/shared/System/Resources/ResourceReader.cs b/src/System.Private.CoreLib/shared/System/Resources/ResourceReader.cs index c0b2f5d4a9df..f5caa42bfd93 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/ResourceReader.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/ResourceReader.cs @@ -993,7 +993,7 @@ internal sealed class ResourceEnumerator : IDictionaryEnumerator private const int ENUM_DONE = int.MinValue; private const int ENUM_NOT_STARTED = -1; - private ResourceReader _reader; + private readonly ResourceReader _reader; private bool _currentIsValid; private int _currentName; private int _dataPosition; // cached for case-insensitive table diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs index ee9250b2d97c..315e9e3b9383 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs @@ -7,7 +7,7 @@ namespace System.Runtime.CompilerServices [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] public sealed class DateTimeConstantAttribute : CustomConstantAttribute { - private DateTime _date; + private readonly DateTime _date; public DateTimeConstantAttribute(long ticks) { diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs index 521a3abe9cb6..abfab1cbebf0 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs @@ -9,7 +9,7 @@ namespace System.Runtime.CompilerServices [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] public sealed class DecimalConstantAttribute : Attribute { - private decimal _dec; + private readonly decimal _dec; [CLSCompliant(false)] public DecimalConstantAttribute( diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ArrayWithOffset.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ArrayWithOffset.cs index 600b7748589e..5d7396b92c5d 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ArrayWithOffset.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ArrayWithOffset.cs @@ -13,9 +13,9 @@ namespace System.Runtime.InteropServices { public struct ArrayWithOffset { - private object? m_array; - private int m_offset; - private int m_count; + private readonly object? m_array; + private readonly int m_offset; + private readonly int m_count; // From MAX_SIZE_FOR_INTEROP in mlinfo.h private const int MaxSizeForInterop = 0x7ffffff0; diff --git a/src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.cs b/src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.cs index 3d1f0caafad6..9931ad75dc2d 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.cs @@ -134,7 +134,7 @@ private static long LastTimeCheckingAddressSpace // in the critical finalizer. private static long s_failPointReservedMemory; - private ulong _reservedMemory; // The size of this request (from user) + private readonly ulong _reservedMemory; // The size of this request (from user) private bool _mustSubtractReservation; // Did we add data to SharedStatics? // We can remove this link demand in a future version - we will @@ -358,16 +358,16 @@ internal static ulong MemoryFailPointReservedMemory [Serializable] internal sealed class MemoryFailPointState { - private ulong _segmentSize; - private int _allocationSizeInMB; - private bool _needPageFile; - private bool _needAddressSpace; - private bool _needContiguousVASpace; - private ulong _availPageFile; - private ulong _totalFreeAddressSpace; - private long _lastKnownFreeAddressSpace; - private ulong _reservedMem; - private string _stackTrace; // Where did we fail, for additional debugging. + private readonly ulong _segmentSize; + private readonly int _allocationSizeInMB; + private readonly bool _needPageFile; + private readonly bool _needAddressSpace; + private readonly bool _needContiguousVASpace; + private readonly ulong _availPageFile; + private readonly ulong _totalFreeAddressSpace; + private readonly long _lastKnownFreeAddressSpace; + private readonly ulong _reservedMem; + private readonly string _stackTrace; // Where did we fail, for additional debugging. internal MemoryFailPointState(int allocationSizeInMB, ulong segmentSize, bool needPageFile, bool needAddressSpace, bool needContiguousVASpace, ulong availPageFile, ulong totalFreeAddressSpace, long lastKnownFreeAddressSpace, ulong reservedMem) { diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Remoting/ObjectHandle.cs b/src/System.Private.CoreLib/shared/System/Runtime/Remoting/ObjectHandle.cs index 993b14c143e9..b5294ba80165 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Remoting/ObjectHandle.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Remoting/ObjectHandle.cs @@ -6,7 +6,7 @@ namespace System.Runtime.Remoting { public class ObjectHandle : MarshalByRefObject { - private object? _wrappedObject; + private readonly object? _wrappedObject; private ObjectHandle() { diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfo.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfo.cs index 999bcfb9936f..3a603d252718 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfo.cs @@ -20,8 +20,8 @@ public sealed class SerializationInfo private object?[] _values; private Type[] _types; private int _count; - private Dictionary _nameToIndex; - private IFormatterConverter _converter; + private readonly Dictionary _nameToIndex; + private readonly IFormatterConverter _converter; private string _rootTypeName; private string _rootTypeAssemblyName; private Type _rootType; diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Versioning/TargetFrameworkAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/Versioning/TargetFrameworkAttribute.cs index 91b3df6ebe0c..df3011e9be22 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Versioning/TargetFrameworkAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Versioning/TargetFrameworkAttribute.cs @@ -17,7 +17,7 @@ namespace System.Runtime.Versioning [AttributeUsageAttribute(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] public sealed class TargetFrameworkAttribute : Attribute { - private string _frameworkName; // A target framework moniker + private readonly string _frameworkName; // A target framework moniker private string? _frameworkDisplayName; // The frameworkName parameter is intended to be the string form of a FrameworkName instance. diff --git a/src/System.Private.CoreLib/shared/System/StringComparer.cs b/src/System.Private.CoreLib/shared/System/StringComparer.cs index 28242fddb53a..f55a098306c7 100644 --- a/src/System.Private.CoreLib/shared/System/StringComparer.cs +++ b/src/System.Private.CoreLib/shared/System/StringComparer.cs @@ -173,7 +173,7 @@ public sealed class CultureAwareComparer : StringComparer, ISerializable private const CompareOptions ValidCompareMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort); private readonly CompareInfo _compareInfo; // Do not rename (binary serialization) - private CompareOptions _options; + private readonly CompareOptions _options; internal CultureAwareComparer(CultureInfo culture, CompareOptions options) : this(culture.CompareInfo, options) { } diff --git a/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs b/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs index d69d1c7f7450..2a1edefc229f 100644 --- a/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs @@ -59,7 +59,7 @@ internal sealed class InternalDecoderBestFitFallbackBuffer : DecoderFallbackBuff private char _cBestFit = '\0'; private int _iCount = -1; private int _iSize; - private InternalDecoderBestFitFallback _oFallback; + private readonly InternalDecoderBestFitFallback _oFallback; // Private object for locking instead of locking on a public type for SQL reliability work. private static object? s_InternalSyncObject; diff --git a/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs b/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs index 865f2ea1c1f4..a1cce71174ad 100644 --- a/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs @@ -106,8 +106,8 @@ private void Throw(byte[] bytesUnknown, int index) [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class DecoderFallbackException : ArgumentException { - private byte[]? _bytesUnknown = null; - private int _index = 0; + private readonly byte[]? _bytesUnknown = null; + private readonly int _index = 0; public DecoderFallbackException() : base(SR.Arg_ArgumentException) diff --git a/src/System.Private.CoreLib/shared/System/Text/DecoderNLS.cs b/src/System.Private.CoreLib/shared/System/Text/DecoderNLS.cs index 7ccaead4d205..20c40c35f8ec 100644 --- a/src/System.Private.CoreLib/shared/System/Text/DecoderNLS.cs +++ b/src/System.Private.CoreLib/shared/System/Text/DecoderNLS.cs @@ -22,7 +22,7 @@ namespace System.Text internal class DecoderNLS : Decoder { // Remember our encoding - private Encoding _encoding; + private readonly Encoding _encoding; private bool _mustFlush; internal bool _throwOnOverflow; internal int _bytesUsed; diff --git a/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs b/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs index a609b31656a5..bbb15d45f6ff 100644 --- a/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs @@ -9,7 +9,7 @@ namespace System.Text public sealed class DecoderReplacementFallback : DecoderFallback { // Our variables - private string _strDefault; + private readonly string _strDefault; // Construction. Default replacement fallback uses no best fit and ? replacement string public DecoderReplacementFallback() : this("?") @@ -102,7 +102,7 @@ public override int GetHashCode() public sealed class DecoderReplacementFallbackBuffer : DecoderFallbackBuffer { // Store our default string - private string _strDefault; + private readonly string _strDefault; private int _fallbackCount = -1; private int _fallbackIndex = -1; diff --git a/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs b/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs index eb443e6dcd8a..2cc35e789a50 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs @@ -57,7 +57,7 @@ internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuff { // Our variables private char _cBestFit = '\0'; - private InternalEncoderBestFitFallback _oFallback; + private readonly InternalEncoderBestFitFallback _oFallback; private int _iCount = -1; private int _iSize; diff --git a/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs b/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs index e55cfb6c679e..3df6accef314 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs @@ -99,10 +99,10 @@ public override int Remaining [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class EncoderFallbackException : ArgumentException { - private char _charUnknown; - private char _charUnknownHigh; - private char _charUnknownLow; - private int _index; + private readonly char _charUnknown; + private readonly char _charUnknownHigh; + private readonly char _charUnknownLow; + private readonly int _index; public EncoderFallbackException() : base(SR.Arg_ArgumentException) diff --git a/src/System.Private.CoreLib/shared/System/Text/EncoderNLS.cs b/src/System.Private.CoreLib/shared/System/Text/EncoderNLS.cs index 12d020c9c6b1..ea63926b94ea 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncoderNLS.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncoderNLS.cs @@ -24,7 +24,7 @@ internal class EncoderNLS : Encoder { // Need a place for the last left over character, most of our encodings use this internal char _charLeftOver; - private Encoding _encoding; + private readonly Encoding _encoding; private bool _mustFlush; internal bool _throwOnOverflow; internal int _charsUsed; diff --git a/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs b/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs index 5eb743bb488e..47a4204aa50f 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs @@ -11,7 +11,7 @@ namespace System.Text public sealed class EncoderReplacementFallback : EncoderFallback { // Our variables - private string _strDefault; + private readonly string _strDefault; // Construction. Default replacement fallback uses no best fit and ? replacement string public EncoderReplacementFallback() : this("?") @@ -103,7 +103,7 @@ public override int GetHashCode() public sealed class EncoderReplacementFallbackBuffer : EncoderFallbackBuffer { // Store our default string - private string _strDefault; + private readonly string _strDefault; private int _fallbackCount = -1; private int _fallbackIndex = -1; diff --git a/src/System.Private.CoreLib/shared/System/Text/Encoding.cs b/src/System.Private.CoreLib/shared/System/Text/Encoding.cs index b91fcbae26c5..2fba2b2fd9f1 100644 --- a/src/System.Private.CoreLib/shared/System/Text/Encoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/Encoding.cs @@ -1197,7 +1197,7 @@ internal void ThrowCharsOverflow(DecoderNLS? decoder, bool nothingDecoded) internal sealed class DefaultEncoder : Encoder, IObjectReference { - private Encoding _encoding; + private readonly Encoding _encoding; public DefaultEncoder(Encoding encoding) { @@ -1262,7 +1262,7 @@ public override unsafe int GetBytes(char* chars, int charCount, internal sealed class DefaultDecoder : Decoder, IObjectReference { - private Encoding _encoding; + private readonly Encoding _encoding; public DefaultDecoder(Encoding encoding) { @@ -1337,15 +1337,15 @@ public override unsafe int GetChars(byte* bytes, int byteCount, internal class EncodingCharBuffer { private unsafe char* _chars; - private unsafe char* _charStart; - private unsafe char* _charEnd; + private readonly unsafe char* _charStart; + private readonly unsafe char* _charEnd; private int _charCountResult = 0; - private Encoding _enc; - private DecoderNLS? _decoder; - private unsafe byte* _byteStart; - private unsafe byte* _byteEnd; + private readonly Encoding _enc; + private readonly DecoderNLS? _decoder; + private readonly unsafe byte* _byteStart; + private readonly unsafe byte* _byteEnd; private unsafe byte* _bytes; - private DecoderFallbackBuffer _fallbackBuffer; + private readonly DecoderFallbackBuffer _fallbackBuffer; internal unsafe EncodingCharBuffer(Encoding enc, DecoderNLS? decoder, char* charStart, int charCount, byte* byteStart, int byteCount) @@ -1510,14 +1510,14 @@ internal int Count internal class EncodingByteBuffer { private unsafe byte* _bytes; - private unsafe byte* _byteStart; - private unsafe byte* _byteEnd; + private readonly unsafe byte* _byteStart; + private readonly unsafe byte* _byteEnd; private unsafe char* _chars; - private unsafe char* _charStart; - private unsafe char* _charEnd; + private readonly unsafe char* _charStart; + private readonly unsafe char* _charEnd; private int _byteCountResult = 0; - private Encoding _enc; - private EncoderNLS? _encoder; + private readonly Encoding _enc; + private readonly EncoderNLS? _encoder; internal EncoderFallbackBuffer fallbackBuffer; internal unsafe EncodingByteBuffer(Encoding inEncoding, EncoderNLS? inEncoder, diff --git a/src/System.Private.CoreLib/shared/System/Text/EncodingProvider.cs b/src/System.Private.CoreLib/shared/System/Text/EncodingProvider.cs index d65dff932ff0..dc96417dfe48 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncodingProvider.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncodingProvider.cs @@ -130,7 +130,7 @@ internal static void AddProvider(EncodingProvider provider) return null; } - private static object s_InternalSyncObject = new object(); + private static readonly object s_InternalSyncObject = new object(); private static volatile EncodingProvider[]? s_providers; } } diff --git a/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs b/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs index 823a13c83b62..2e414cf8d0f4 100644 --- a/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs @@ -42,7 +42,7 @@ public class UTF7Encoding : Encoding // This array has a size of 128. private bool[] _directEncode = null!; - private bool _allowOptionals; + private readonly bool _allowOptionals; private const int UTF7_CODEPAGE = 65000; diff --git a/src/System.Private.CoreLib/shared/System/Threading/ReaderWriterLockSlim.cs b/src/System.Private.CoreLib/shared/System/Threading/ReaderWriterLockSlim.cs index a06281e2a310..c1b0e301b3f4 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/ReaderWriterLockSlim.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/ReaderWriterLockSlim.cs @@ -83,7 +83,7 @@ public class ReaderWriterLockSlim : IDisposable // Every lock instance has a unique ID, which is used by ReaderWriterCount to associate itself with the lock // without holding a reference to it. private static long s_nextLockID; - private long _lockID; + private readonly long _lockID; // See comments on ReaderWriterCount. [ThreadStatic] @@ -235,8 +235,8 @@ public void EnterReadLock() // private struct TimeoutTracker { - private int _total; - private int _start; + private readonly int _total; + private readonly int _start; public TimeoutTracker(TimeSpan timeout) { diff --git a/src/System.Private.CoreLib/shared/System/Threading/Tasks/Future.cs b/src/System.Private.CoreLib/shared/System/Threading/Tasks/Future.cs index 0a981a382acc..21c5eae8c5d3 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/Tasks/Future.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/Tasks/Future.cs @@ -1378,7 +1378,7 @@ internal Task ContinueWith(Func, object?, // Proxy class for better debugging experience internal class SystemThreadingTasks_FutureDebugView { - private Task m_task; + private readonly Task m_task; public SystemThreadingTasks_FutureDebugView(Task task) { diff --git a/src/System.Private.CoreLib/shared/System/Threading/Tasks/FutureFactory.cs b/src/System.Private.CoreLib/shared/System/Threading/Tasks/FutureFactory.cs index c9819ed4247c..8ad7a5a85685 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/Tasks/FutureFactory.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/Tasks/FutureFactory.cs @@ -32,10 +32,10 @@ public class TaskFactory // Should we be thinking about a TaskFactoryBase class? // member variables - private CancellationToken m_defaultCancellationToken; - private TaskScheduler? m_defaultScheduler; - private TaskCreationOptions m_defaultCreationOptions; - private TaskContinuationOptions m_defaultContinuationOptions; + private readonly CancellationToken m_defaultCancellationToken; + private readonly TaskScheduler? m_defaultScheduler; + private readonly TaskCreationOptions m_defaultCreationOptions; + private readonly TaskContinuationOptions m_defaultContinuationOptions; private TaskScheduler DefaultScheduler => m_defaultScheduler ?? TaskScheduler.Current; diff --git a/src/System.Private.CoreLib/shared/System/Threading/Tasks/Task.cs b/src/System.Private.CoreLib/shared/System/Threading/Tasks/Task.cs index c56e3798d702..53d35fbdf1cb 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/Tasks/Task.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/Tasks/Task.cs @@ -6287,7 +6287,7 @@ void IThreadPoolWorkItem.Execute() // Proxy class for better debugging experience internal class SystemThreadingTasks_TaskDebugView { - private Task m_task; + private readonly Task m_task; public SystemThreadingTasks_TaskDebugView(Task task) { diff --git a/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskScheduler.cs b/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskScheduler.cs index f9db0675b2b7..75b8cab3ec32 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskScheduler.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskScheduler.cs @@ -569,7 +569,7 @@ public IEnumerable? ScheduledTasks /// internal sealed class SynchronizationContextTaskScheduler : TaskScheduler { - private SynchronizationContext m_synchronizationContext; + private readonly SynchronizationContext m_synchronizationContext; /// /// Constructs a SynchronizationContextTaskScheduler associated with @@ -653,7 +653,7 @@ public override int MaximumConcurrencyLevel /// public class UnobservedTaskExceptionEventArgs : EventArgs { - private AggregateException? m_exception; + private readonly AggregateException? m_exception; internal bool m_observed = false; /// diff --git a/src/System.Private.CoreLib/shared/System/Threading/ThreadLocal.cs b/src/System.Private.CoreLib/shared/System/Threading/ThreadLocal.cs index 68c589774686..0056172e3958 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/ThreadLocal.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/ThreadLocal.cs @@ -687,7 +687,7 @@ private class IdManager private int _nextIdToTry = 0; // Stores whether each ID is free or not. Additionally, the object is also used as a lock for the IdManager. - private List _freeIds = new List(); + private readonly List _freeIds = new List(); internal int GetId() { @@ -741,7 +741,7 @@ internal void ReturnId(int id) private class FinalizationHelper { internal LinkedSlotVolatile[] SlotArray; - private bool _trackAllValues; + private readonly bool _trackAllValues; internal FinalizationHelper(LinkedSlotVolatile[] slotArray, bool trackAllValues) { diff --git a/src/System.Private.CoreLib/shared/System/Threading/ThreadPool.cs b/src/System.Private.CoreLib/shared/System/Threading/ThreadPool.cs index 4050d03af262..6925af04265f 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/ThreadPool.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/ThreadPool.cs @@ -407,11 +407,11 @@ public int Count internal bool loggingEnabled; internal readonly ConcurrentQueue workItems = new ConcurrentQueue(); // SOS's ThreadPool command depends on this name - private Internal.PaddingFor32 pad1; + private readonly Internal.PaddingFor32 pad1; private volatile int numOutstandingThreadRequests = 0; - private Internal.PaddingFor32 pad2; + private readonly Internal.PaddingFor32 pad2; public ThreadPoolWorkQueue() { @@ -911,9 +911,9 @@ public override void Execute() internal sealed class _ThreadPoolWaitOrTimerCallback { - private WaitOrTimerCallback _waitOrTimerCallback; - private ExecutionContext? _executionContext; - private object? _state; + private readonly WaitOrTimerCallback _waitOrTimerCallback; + private readonly ExecutionContext? _executionContext; + private readonly object? _state; private static readonly ContextCallback _ccbt = new ContextCallback(WaitOrTimerCallback_Context_t); private static readonly ContextCallback _ccbf = new ContextCallback(WaitOrTimerCallback_Context_f); diff --git a/src/System.Private.CoreLib/shared/System/Threading/Timer.cs b/src/System.Private.CoreLib/shared/System/Threading/Timer.cs index 722c0b3e709f..b3088c7f362b 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/Timer.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/Timer.cs @@ -124,7 +124,7 @@ private bool EnsureTimerFiresBy(uint requestedDuration) private const int ShortTimersThresholdMilliseconds = 333; // Time when Pause was called - private volatile int _pauseTicks = 0; + private readonly int _pauseTicks = 0; // Fire any timers that have expired, and update the native timer to schedule the rest of them. // We're in a thread pool work item here, and if there are multiple timers to be fired, we want diff --git a/src/System.Private.CoreLib/shared/System/TypeInitializationException.cs b/src/System.Private.CoreLib/shared/System/TypeInitializationException.cs index a0f5d086631b..05d424f6a24c 100644 --- a/src/System.Private.CoreLib/shared/System/TypeInitializationException.cs +++ b/src/System.Private.CoreLib/shared/System/TypeInitializationException.cs @@ -23,7 +23,7 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class TypeInitializationException : SystemException { - private string? _typeName; + private readonly string? _typeName; // This exception is not creatable without specifying the // inner exception. diff --git a/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventArgs.cs b/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventArgs.cs index c214afdc7113..ed4ef11c25e7 100644 --- a/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventArgs.cs +++ b/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventArgs.cs @@ -6,8 +6,8 @@ namespace System { public class UnhandledExceptionEventArgs : EventArgs { - private object _exception; - private bool _isTerminating; + private readonly object _exception; + private readonly bool _isTerminating; public UnhandledExceptionEventArgs(object exception, bool isTerminating) { diff --git a/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs b/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs index 1e38807c3e8f..fb052618a39b 100644 --- a/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs +++ b/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs @@ -573,21 +573,21 @@ internal sealed class LicenseInteropProxy private static readonly Type? s_licenseExceptionType = Type.GetType("System.ComponentModel.LicenseException, System.ComponentModel.TypeConverter", throwOnError: false); // LicenseManager - private MethodInfo _createWithContext; + private readonly MethodInfo _createWithContext; // LicenseInteropHelper - private MethodInfo _validateTypeAndReturnDetails; - private MethodInfo _getCurrentContextInfo; + private readonly MethodInfo _validateTypeAndReturnDetails; + private readonly MethodInfo _getCurrentContextInfo; // CLRLicenseContext - private MethodInfo _createDesignContext; - private MethodInfo _createRuntimeContext; + private readonly MethodInfo _createDesignContext; + private readonly MethodInfo _createRuntimeContext; // LicenseContext - private MethodInfo _setSavedLicenseKey; + private readonly MethodInfo _setSavedLicenseKey; - private Type _licInfoHelper; - private MethodInfo _licInfoHelperContains; + private readonly Type _licInfoHelper; + private readonly MethodInfo _licInfoHelperContains; // RCW Activation private object? _licContext; diff --git a/src/System.Private.CoreLib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs b/src/System.Private.CoreLib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs index c8bf060dfcfb..2a8898e008cc 100644 --- a/src/System.Private.CoreLib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs +++ b/src/System.Private.CoreLib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs @@ -356,7 +356,7 @@ object ICollection.SyncRoot private struct DictionaryEnumerator : IDictionaryEnumerator { private readonly IDictionary m_dictionary; - private IEnumerator> m_enumerator; + private readonly IEnumerator> m_enumerator; public DictionaryEnumerator(IDictionary dictionary) { diff --git a/src/System.Private.CoreLib/src/System/Diagnostics/Eventing/EventPipe.cs b/src/System.Private.CoreLib/src/System/Diagnostics/Eventing/EventPipe.cs index 1188495a6260..62585e4b569c 100644 --- a/src/System.Private.CoreLib/src/System/Diagnostics/Eventing/EventPipe.cs +++ b/src/System.Private.CoreLib/src/System/Diagnostics/Eventing/EventPipe.cs @@ -35,9 +35,9 @@ internal struct EventPipeSessionInfo internal struct EventPipeProviderConfiguration { [MarshalAs(UnmanagedType.LPWStr)] - private string m_providerName; - private ulong m_keywords; - private uint m_loggingLevel; + private readonly string m_providerName; + private readonly ulong m_keywords; + private readonly uint m_loggingLevel; [MarshalAs(UnmanagedType.LPWStr)] private readonly string? m_filterData; @@ -93,10 +93,10 @@ internal sealed class EventPipeWaitHandle : WaitHandle internal sealed class EventPipeConfiguration { - private string m_outputFile; - private EventPipeSerializationFormat m_format; - private uint m_circularBufferSizeInMB; - private List m_providers; + private readonly string m_outputFile; + private readonly EventPipeSerializationFormat m_format; + private readonly uint m_circularBufferSizeInMB; + private readonly List m_providers; private TimeSpan m_minTimeBetweenSamples = TimeSpan.FromMilliseconds(1); internal EventPipeConfiguration( diff --git a/src/System.Private.CoreLib/src/System/Diagnostics/Eventing/EventPipeEventDispatcher.cs b/src/System.Private.CoreLib/src/System/Diagnostics/Eventing/EventPipeEventDispatcher.cs index ff9a7016c958..10d9c46697e0 100644 --- a/src/System.Private.CoreLib/src/System/Diagnostics/Eventing/EventPipeEventDispatcher.cs +++ b/src/System.Private.CoreLib/src/System/Diagnostics/Eventing/EventPipeEventDispatcher.cs @@ -25,7 +25,7 @@ internal EventListenerSubscription(EventKeywords matchAnyKeywords, EventLevel le internal static readonly EventPipeEventDispatcher Instance = new EventPipeEventDispatcher(); - private IntPtr m_RuntimeProviderID; + private readonly IntPtr m_RuntimeProviderID; private ulong m_sessionID = 0; private DateTime m_syncTimeUtc; @@ -33,12 +33,12 @@ internal EventListenerSubscription(EventKeywords matchAnyKeywords, EventLevel le private long m_timeQPCFrequency; private bool m_stopDispatchTask; - private EventPipeWaitHandle m_dispatchTaskWaitHandle = new EventPipeWaitHandle(); + private readonly EventPipeWaitHandle m_dispatchTaskWaitHandle = new EventPipeWaitHandle(); private Task? m_dispatchTask = null; - private object m_dispatchControlLock = new object(); - private Dictionary m_subscriptions = new Dictionary(); + private readonly object m_dispatchControlLock = new object(); + private readonly Dictionary m_subscriptions = new Dictionary(); - private static uint DefaultEventListenerCircularMBSize = 10; + private const uint DefaultEventListenerCircularMBSize = 10; private EventPipeEventDispatcher() { diff --git a/src/System.Private.CoreLib/src/System/Exception.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Exception.CoreCLR.cs index 26b21089a3e8..979f40f2e3cd 100644 --- a/src/System.Private.CoreLib/src/System/Exception.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Exception.CoreCLR.cs @@ -69,7 +69,7 @@ internal class __RestrictedErrorObject { // Hold the error object instance but don't serialize/deserialize it [NonSerialized] - private object _realErrorObject; + private readonly object _realErrorObject; internal __RestrictedErrorObject(object errorObject) { @@ -345,7 +345,7 @@ internal void RestoreDispatchState(in DispatchState dispatchState) private MethodBase? _exceptionMethod; //Needed for serialization. internal string? _message; private IDictionary? _data; - private Exception? _innerException; + private readonly Exception? _innerException; private string? _helpURL; private object? _stackTrace; private object? _watsonBuckets; @@ -357,11 +357,11 @@ internal void RestoreDispatchState(in DispatchState dispatchState) // DynamicMethodDescs alive for the lifetime of the exception. We do this because // the _stackTrace field holds MethodDescs, and a DynamicMethodDesc can be destroyed // unless a System.Resolver object roots it. - private object? _dynamicMethods; + private readonly object? _dynamicMethods; private string? _source; // Mainly used by VB. private UIntPtr _ipForWatsonBuckets; // Used to persist the IP for Watson Bucketing - private IntPtr _xptrs; // Internal EE stuff - private int _xcode = _COMPlusExceptionCode; // Internal EE stuff + private readonly IntPtr _xptrs; // Internal EE stuff + private readonly int _xcode = _COMPlusExceptionCode; // Internal EE stuff #pragma warning restore CA1823 #pragma warning restore 414 diff --git a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs index 7801ffca439e..66128fc7910f 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs @@ -9,7 +9,7 @@ namespace System.Runtime.CompilerServices [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class TypeDependencyAttribute : Attribute { - private string typeName; + private readonly string typeName; public TypeDependencyAttribute(string typeName) { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsInfo.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsInfo.cs index 5a3bc042dd50..e65614b92fea 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsInfo.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsInfo.cs @@ -7,7 +7,7 @@ namespace System.Runtime.InteropServices internal class ComEventsInfo { private ComEventsSink? _sinks; - private object _rcw; + private readonly object _rcw; private ComEventsInfo(object rcw) { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsMethod.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsMethod.cs index 10ef6e5db930..53d7a5d71681 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsMethod.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsMethod.cs @@ -100,7 +100,7 @@ private void PreProcessSignature() /// Since multicast delegate's built-in chaining supports only chaining instances of the same type, /// we need to complement this design by using an explicit linked list data structure. /// - private List _delegateWrappers = new List(); + private readonly List _delegateWrappers = new List(); private readonly int _dispid; private ComEventsMethod? _next; diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumeratorViewOfEnumVariant.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumeratorViewOfEnumVariant.cs index 6b1c418862f0..ecb583f2b9c5 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumeratorViewOfEnumVariant.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumeratorViewOfEnumVariant.cs @@ -11,7 +11,7 @@ internal class EnumeratorViewOfEnumVariant : ICustomAdapter, IEnumerator { private readonly IEnumVARIANT _enumVariantObject; private bool _fetchedLastObject; - private object[] _nextArray = new object[1]; + private readonly object[] _nextArray = new object[1]; private object? _current; public EnumeratorViewOfEnumVariant(IEnumVARIANT enumVariantObject) diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs index 8fe16d11faff..3c3f853b1de1 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs @@ -8,7 +8,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false, Inherited = false)] public sealed class DefaultInterfaceAttribute : Attribute { - private Type m_defaultInterface; + private readonly Type m_defaultInterface; public DefaultInterfaceAttribute(Type defaultInterface) { @@ -55,11 +55,11 @@ public InterfaceImplementedInVersionAttribute(Type interfaceType, byte majorVers public byte RevisionVersion => m_revisionVersion; - private Type m_interfaceType; - private byte m_majorVersion; - private byte m_minorVersion; - private byte m_buildVersion; - private byte m_revisionVersion; + private readonly Type m_interfaceType; + private readonly byte m_majorVersion; + private readonly byte m_minorVersion; + private readonly byte m_buildVersion; + private readonly byte m_revisionVersion; } // Applies to read-only array parameters @@ -82,7 +82,7 @@ public WriteOnlyArrayAttribute() { } [AttributeUsage(AttributeTargets.ReturnValue | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] public sealed class ReturnValueNameAttribute : Attribute { - private string m_Name; + private readonly string m_Name; public ReturnValueNameAttribute(string name) { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs index b4b1b59670f0..edad524b4c30 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs @@ -11,8 +11,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime { internal class CLRIPropertyValueImpl : IPropertyValue { - private PropertyType _type; - private object _data; + private readonly PropertyType _type; + private readonly object _data; // Numeric scalar types which participate in coersion private static volatile Tuple[]? s_numericScalarTypes; diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs index 8ee1ff778366..23867cdaea84 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs @@ -9,7 +9,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { internal sealed class CLRIReferenceImpl : CLRIPropertyValueImpl, IReference, IGetProxyTarget { - private T _value; + private readonly T _value; public CLRIReferenceImpl(PropertyType type, T obj) : base(type, obj!) @@ -60,8 +60,8 @@ internal sealed class CLRIReferenceArrayImpl : CLRIPropertyValueImpl, IReferenceArray, IList // Jupiter data binding needs IList/IEnumerable { - private T[] _value; - private IList _list; + private readonly T[] _value; + private readonly IList _list; public CLRIReferenceArrayImpl(PropertyType type, T[] obj) : base(type, obj) diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs index fbab70b97461..49bdab07add9 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs @@ -167,9 +167,9 @@ public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) internal struct IKeyValuePairEnumerator : IEnumerator> { - private KeyValuePair[] _array; - private int _start; - private int _end; + private readonly KeyValuePair[] _array; + private readonly int _start; + private readonly int _end; private int _current; internal IKeyValuePairEnumerator(KeyValuePair[] items, int first, int end) diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs index 24fbaa3bd54b..d5a8a01e3da7 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs @@ -11,7 +11,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // internal sealed class CustomPropertyImpl : ICustomProperty { - private PropertyInfo m_property; + private readonly PropertyInfo m_property; // // Constructor diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs index a2772d98c45f..096df0be7b6a 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs @@ -41,7 +41,7 @@ private EnumerableToBindableIterableAdapter() internal sealed class NonGenericToGenericEnumerator : IEnumerator { - private IEnumerator enumerator; + private readonly IEnumerator enumerator; public NonGenericToGenericEnumerator(IEnumerator enumerator) { this.enumerator = enumerator; } @@ -63,7 +63,7 @@ internal IBindableIterator First_Stub() // Adapter class which holds a managed IEnumerator, exposing it as a Windows Runtime IIterator internal sealed class EnumeratorToIteratorAdapter : IIterator, IBindableIterator { - private IEnumerator m_enumerator; + private readonly IEnumerator m_enumerator; private bool m_firstItem = true; private bool m_hasCurrent; diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs index afb93ea24f27..705379f5249d 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs @@ -14,7 +14,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public sealed class EventRegistrationTokenTable where T : class { // Note this dictionary is also used as the synchronization object for this table - private Dictionary m_tokens = new Dictionary(); + private readonly Dictionary m_tokens = new Dictionary(); // Cached multicast delegate which will invoke all of the currently registered delegates. This // will be accessed frequently in common coding paterns, so we don't want to calculate it repeatedly. diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs index 6191bc9d558b..22e3c8880486 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs @@ -127,8 +127,8 @@ internal class ICustomPropertyProviderProxy : IGetProxyTarget, IBindableVector, // IBindableVector -> IBindableVector/IVector IBindableVectorView // IBindableVectorView -> IBindableVectorView/IVectorView { - private object _target; - private InterfaceForwardingSupport _flags; + private readonly object _target; + private readonly InterfaceForwardingSupport _flags; internal ICustomPropertyProviderProxy(object target, InterfaceForwardingSupport flags) { @@ -285,7 +285,7 @@ IBindableVectorView IBindableVector.GetView() private sealed class IVectorViewToIBindableVectorViewAdapter : IBindableVectorView { - private IVectorView _vectorView; + private readonly IVectorView _vectorView; public IVectorViewToIBindableVectorViewAdapter(IVectorView vectorView) { @@ -482,7 +482,7 @@ IBindableIterator IBindableIterable.First() private sealed class IteratorOfTToIteratorAdapter : IBindableIterator { - private IIterator _iterator; + private readonly IIterator _iterator; public IteratorOfTToIteratorAdapter(IIterator iterator) { _iterator = iterator; } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs index b26e9f2da709..1fb47a1e1808 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs @@ -68,7 +68,7 @@ private BindableIterableToEnumerableAdapter() private sealed class NonGenericToGenericIterator : IIterator { - private IBindableIterator iterator; + private readonly IBindableIterator iterator; public NonGenericToGenericIterator(IBindableIterator iterator) { this.iterator = iterator; } @@ -96,7 +96,7 @@ internal IEnumerator GetEnumerator_Stub() // Also IEnumerator throws an exception when we call Current after reaching the end of collection. internal sealed class IteratorToEnumeratorAdapter : IEnumerator { - private IIterator m_iterator; + private readonly IIterator m_iterator; private bool m_hadCurrent; private T m_current = default!; private bool m_isInitialized; diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs index 01e3d28d8524..bf3392b6ad4e 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs @@ -25,7 +25,7 @@ internal interface IManagedActivationFactory [ClassInterface(ClassInterfaceType.None)] internal sealed class ManagedActivationFactory : IActivationFactory, IManagedActivationFactory { - private Type m_type; + private readonly Type m_type; internal ManagedActivationFactory(Type type) { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs index 8d1607602075..9a009c86e62a 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs @@ -118,7 +118,7 @@ internal static int GetRegistrationTokenCacheSize() // internal struct EventRegistrationTokenList { - private EventRegistrationToken firstToken; // Optimization for common case where there is only one token + private readonly EventRegistrationToken firstToken; // Optimization for common case where there is only one token private List? restTokens; // Rest of the tokens internal EventRegistrationTokenList(EventRegistrationToken token) @@ -384,7 +384,7 @@ public int GetHashCode(EventCacheKey key) // internal class EventRegistrationTokenListWithCount { - private TokenListCount _tokenListCount; + private readonly TokenListCount _tokenListCount; private EventRegistrationTokenList _tokenList; internal EventRegistrationTokenListWithCount(TokenListCount tokenListCount, EventRegistrationToken token) @@ -517,7 +517,7 @@ internal struct EventCacheEntry new Dictionary(); // Prevent add/remove handler code to run at the same with with cache cleanup code - private static volatile MyReaderWriterLock s_eventCacheRWLock = new MyReaderWriterLock(); + private static readonly MyReaderWriterLock s_eventCacheRWLock = new MyReaderWriterLock(); // Get InstanceKey to use in the cache private static object GetInstanceKey(Action removeMethod) diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs index 273b270f3778..b0ae3b957509 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs @@ -8,7 +8,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { internal static class WindowsRuntimeMetadata { - private static EventHandler? DesignerNamespaceResolve; + private static readonly EventHandler? DesignerNamespaceResolve; internal static string[]? OnDesignerNamespaceResolve(string namespaceName) { @@ -48,8 +48,8 @@ internal static class WindowsRuntimeMetadata internal class DesignerNamespaceResolveEventArgs : EventArgs { - private string _NamespaceName; - private Collection _ResolvedAssemblyFiles; + private readonly string _NamespaceName; + private readonly Collection _ResolvedAssemblyFiles; public Collection ResolvedAssemblyFiles { diff --git a/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs b/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs index 6be41e45762a..5e8b378ebd04 100644 --- a/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs @@ -223,7 +223,7 @@ private class MemberInfoCache where T : MemberInfo private bool m_cacheComplete; // This is the strong reference back to the cache - private RuntimeTypeCache m_runtimeTypeCache; + private readonly RuntimeTypeCache m_runtimeTypeCache; #endregion #region Constructor @@ -1401,14 +1401,14 @@ internal T[] GetMemberList(MemberListType listType, string? name, CacheType cach #endregion #region Private Data Members - private RuntimeType m_runtimeType; + private readonly RuntimeType m_runtimeType; private RuntimeType? m_enclosingType; private TypeCode m_typeCode; private string? m_name; private string? m_fullname; private string? m_toString; private string? m_namespace; - private bool m_isGlobal; + private readonly bool m_isGlobal; private bool m_bIsDomainInitialized; private MemberInfoCache? m_methodInfoCache; private MemberInfoCache? m_constructorInfoCache; @@ -2354,7 +2354,7 @@ private static bool FilterApplyMethodBase( #region Private Data Members #pragma warning disable CA1823 - private object m_keepalive; // This will be filled with a LoaderAllocator reference when this RuntimeType represents a collectible type + private readonly object m_keepalive; // This will be filled with a LoaderAllocator reference when this RuntimeType represents a collectible type #pragma warning restore CA1823 private IntPtr m_cache; internal IntPtr m_handle; @@ -3378,7 +3378,7 @@ public override StructLayoutAttribute? StructLayoutAttribute private const BindingFlags BinderGetSetProperty = BindingFlags.GetProperty | BindingFlags.SetProperty; private const BindingFlags BinderGetSetField = BindingFlags.GetField | BindingFlags.SetField; private const BindingFlags BinderNonFieldGetSet = (BindingFlags)0x00FFF300; - private static RuntimeType s_typedRef = (RuntimeType)typeof(TypedReference); + private static readonly RuntimeType s_typedRef = (RuntimeType)typeof(TypedReference); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool CanValueSpecialCast(RuntimeType valueType, RuntimeType targetType); diff --git a/src/System.Private.CoreLib/src/System/Threading/Overlapped.cs b/src/System.Private.CoreLib/src/System/Threading/Overlapped.cs index 3eefadb4cfd5..81dbe64216bf 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Overlapped.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Overlapped.cs @@ -30,8 +30,8 @@ namespace System.Threading internal unsafe class _IOCompletionCallback { - private IOCompletionCallback _ioCompletionCallback; - private ExecutionContext _executionContext; + private readonly IOCompletionCallback _ioCompletionCallback; + private readonly ExecutionContext _executionContext; private uint _errorCode; // Error code private uint _numBytes; // No. of bytes transferred private NativeOverlapped* _pNativeOverlapped; @@ -93,7 +93,7 @@ internal sealed unsafe class OverlappedData internal object? _callback; // IOCompletionCallback or _IOCompletionCallback internal readonly Overlapped _overlapped; private object? _userObject; - private NativeOverlapped * _pNativeOverlapped; + private readonly NativeOverlapped* _pNativeOverlapped; private IntPtr _eventHandle; private int _offsetLow; private int _offsetHigh; diff --git a/src/System.Private.CoreLib/src/System/Threading/Tasks/AsyncCausalityTracer.cs b/src/System.Private.CoreLib/src/System/Threading/Tasks/AsyncCausalityTracer.cs index bad420454c83..23ed7ee59e77 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Tasks/AsyncCausalityTracer.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Tasks/AsyncCausalityTracer.cs @@ -33,7 +33,7 @@ internal static bool LoggingOn //Indicates this information comes from the BCL Library private const WFD.CausalitySource s_CausalitySource = WFD.CausalitySource.Library; - private static WFD.IAsyncCausalityTracerStatics s_TracerFactory = null!; + private static readonly WFD.IAsyncCausalityTracerStatics s_TracerFactory = null!; // The loggers that this Tracer knows about. [Flags] diff --git a/src/System.Private.CoreLib/src/System/TypeNameParser.cs b/src/System.Private.CoreLib/src/System/TypeNameParser.cs index 06eab1938a23..4eff4e36c40d 100644 --- a/src/System.Private.CoreLib/src/System/TypeNameParser.cs +++ b/src/System.Private.CoreLib/src/System/TypeNameParser.cs @@ -89,7 +89,7 @@ internal sealed class TypeNameParser : IDisposable #endregion #region Private Data Members - private SafeTypeNameParserHandle m_NativeParser; + private readonly SafeTypeNameParserHandle m_NativeParser; private static readonly char[] SPECIAL_CHARS = { ',', '[', ']', '&', '*', '+', '\\' }; /* see typeparse.h */ #endregion From bdaf7fa74e3596fb9e635c3d6c9f171a56e44735 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Fri, 9 Aug 2019 11:55:23 -0400 Subject: [PATCH 2/6] Contribute to IDE0019 (use pattern matching) and IDE0066 (use switch expression) --- .../shared/System/AggregateException.cs | 2 +- .../shared/System/Array.cs | 6 +- .../Text/Utf8Formatter/Utf8Formatter.Date.cs | 46 +- .../Text/Utf8Parser/Utf8Parser.Date.cs | 27 +- .../shared/System/Collections/ArrayList.cs | 3 +- .../shared/System/Collections/Comparer.cs | 3 +- .../shared/System/Convert.cs | 61 +- .../shared/System/DateTime.Windows.cs | 11 +- .../shared/System/DateTime.cs | 13 +- .../Diagnostics/Tracing/EventProvider.cs | 18 +- .../Tracing/TraceLogging/Statics.cs | 125 +-- .../shared/System/Enum.cs | 323 ++----- .../shared/System/Environment.cs | 3 +- .../shared/System/Globalization/Calendar.cs | 18 +- .../System/Globalization/CultureInfo.cs | 13 +- .../Globalization/DateTimeFormatInfo.cs | 17 +- .../System/Globalization/HebrewCalendar.cs | 16 +- .../System/Globalization/TimeSpanParse.cs | 40 +- .../shared/System/Guid.cs | 55 +- .../System/Runtime/Intrinsics/X86/Avx2.cs | 912 +++++++----------- .../shared/System/Security/SecurityElement.cs | 3 +- .../shared/System/StringComparer.cs | 25 +- .../shared/System/Text/UTF7Encoding.cs | 3 +- .../Threading/CancellationTokenSource.cs | 21 +- .../shared/System/Threading/Tasks/Task.cs | 7 +- .../System/Threading/Tasks/TaskToApm.cs | 6 +- .../shared/System/Tuple.cs | 152 ++- .../shared/System/ValueTuple.cs | 174 ++-- .../src/System/Attribute.CoreCLR.cs | 45 +- .../src/System/Reflection/CustomAttribute.cs | 77 +- .../src/System/Reflection/MdConstant.cs | 75 +- .../src/System/Reflection/MdFieldInfo.cs | 9 +- .../src/System/Reflection/RtFieldInfo.cs | 7 +- .../Reflection/RuntimeConstructorInfo.cs | 7 +- .../src/System/Reflection/RuntimeEventInfo.cs | 9 +- .../System/Reflection/RuntimeMethodInfo.cs | 7 +- .../System/Reflection/RuntimePropertyInfo.cs | 9 +- .../src/System/RuntimeType.CoreCLR.cs | 6 +- .../src/System/StubHelpers.cs | 7 +- .../src/System/Variant.cs | 237 ++--- 40 files changed, 875 insertions(+), 1723 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/AggregateException.cs b/src/System.Private.CoreLib/shared/System/AggregateException.cs index e0f079fe2390..85277d97ac4b 100644 --- a/src/System.Private.CoreLib/shared/System/AggregateException.cs +++ b/src/System.Private.CoreLib/shared/System/AggregateException.cs @@ -258,7 +258,7 @@ protected AggregateException(SerializationInfo info, StreamingContext context) : } Exception[]? innerExceptions = info.GetValue("InnerExceptions", typeof(Exception[])) as Exception[]; - if (innerExceptions == null) + if (innerExceptions is null) { throw new SerializationException(SR.AggregateException_DeserializationFailure); } diff --git a/src/System.Private.CoreLib/shared/System/Array.cs b/src/System.Private.CoreLib/shared/System/Array.cs index 247b1ea98d12..5a338c3a8008 100644 --- a/src/System.Private.CoreLib/shared/System/Array.cs +++ b/src/System.Private.CoreLib/shared/System/Array.cs @@ -936,9 +936,8 @@ public static int IndexOf(Array array, object? value, int startIndex, int count) return retVal; #endif - object[]? objArray = array as object[]; int endIndex = startIndex + count; - if (objArray != null) + if (array is object[] objArray) { if (value == null) { @@ -1120,9 +1119,8 @@ public static int LastIndexOf(Array array, object? value, int startIndex, int co return retVal; #endif - object[]? objArray = array as object[]; int endIndex = startIndex - count + 1; - if (objArray != null) + if (array is object[] objArray) { if (value == null) { diff --git a/src/System.Private.CoreLib/shared/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.cs b/src/System.Private.CoreLib/shared/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.cs index 74d607634bbe..122c490ccaa2 100644 --- a/src/System.Private.CoreLib/shared/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.cs +++ b/src/System.Private.CoreLib/shared/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.cs @@ -105,23 +105,14 @@ public static bool TryFormat(DateTimeOffset value, Span destination, out i offset = value.Offset; } - switch (symbol) + return symbol switch { - case 'R': - return TryFormatDateTimeR(value.UtcDateTime, destination, out bytesWritten); - - case 'l': - return TryFormatDateTimeL(value.UtcDateTime, destination, out bytesWritten); - - case 'O': - return TryFormatDateTimeO(value.DateTime, value.Offset, destination, out bytesWritten); - - case 'G': - return TryFormatDateTimeG(value.DateTime, offset, destination, out bytesWritten); - - default: - return FormattingHelpers.TryFormatThrowFormatException(out bytesWritten); - } + 'R' => TryFormatDateTimeR(value.UtcDateTime, destination, out bytesWritten), + 'l' => TryFormatDateTimeL(value.UtcDateTime, destination, out bytesWritten), + 'O' => TryFormatDateTimeO(value.DateTime, value.Offset, destination, out bytesWritten), + 'G' => TryFormatDateTimeG(value.DateTime, offset, destination, out bytesWritten), + _ => FormattingHelpers.TryFormatThrowFormatException(out bytesWritten), + }; } /// @@ -149,23 +140,14 @@ public static bool TryFormat(DateTime value, Span destination, out int byt { char symbol = FormattingHelpers.GetSymbolOrDefault(format, 'G'); - switch (symbol) + return symbol switch { - case 'R': - return TryFormatDateTimeR(value, destination, out bytesWritten); - - case 'l': - return TryFormatDateTimeL(value, destination, out bytesWritten); - - case 'O': - return TryFormatDateTimeO(value, Utf8Constants.NullUtcOffset, destination, out bytesWritten); - - case 'G': - return TryFormatDateTimeG(value, Utf8Constants.NullUtcOffset, destination, out bytesWritten); - - default: - return FormattingHelpers.TryFormatThrowFormatException(out bytesWritten); - } + 'R' => TryFormatDateTimeR(value, destination, out bytesWritten), + 'l' => TryFormatDateTimeL(value, destination, out bytesWritten), + 'O' => TryFormatDateTimeO(value, Utf8Constants.NullUtcOffset, destination, out bytesWritten), + 'G' => TryFormatDateTimeG(value, Utf8Constants.NullUtcOffset, destination, out bytesWritten), + _ => FormattingHelpers.TryFormatThrowFormatException(out bytesWritten), + }; } } } diff --git a/src/System.Private.CoreLib/shared/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.cs b/src/System.Private.CoreLib/shared/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.cs index 16721850bb78..7fb6f0c60810 100644 --- a/src/System.Private.CoreLib/shared/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.cs +++ b/src/System.Private.CoreLib/shared/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.cs @@ -121,26 +121,15 @@ public static bool TryParse(ReadOnlySpan source, out DateTime value, out i /// public static bool TryParse(ReadOnlySpan source, out DateTimeOffset value, out int bytesConsumed, char standardFormat = default) { - switch (standardFormat) + return standardFormat switch { - case 'R': - return TryParseDateTimeOffsetR(source, NoFlipCase, out value, out bytesConsumed); - - case 'l': - return TryParseDateTimeOffsetR(source, FlipCase, out value, out bytesConsumed); - - case 'O': - return TryParseDateTimeOffsetO(source, out value, out bytesConsumed, out _); - - case default(char): - return TryParseDateTimeOffsetDefault(source, out value, out bytesConsumed); - - case 'G': - return TryParseDateTimeG(source, out DateTime _, out value, out bytesConsumed); - - default: - return ParserHelpers.TryParseThrowFormatException(out value, out bytesConsumed); - } + 'R' => TryParseDateTimeOffsetR(source, NoFlipCase, out value, out bytesConsumed), + 'l' => TryParseDateTimeOffsetR(source, FlipCase, out value, out bytesConsumed), + 'O' => TryParseDateTimeOffsetO(source, out value, out bytesConsumed, out _), + default(char) => TryParseDateTimeOffsetDefault(source, out value, out bytesConsumed), + 'G' => TryParseDateTimeG(source, out DateTime _, out value, out bytesConsumed), + _ => ParserHelpers.TryParseThrowFormatException(out value, out bytesConsumed), + }; } private const uint FlipCase = 0x00000020u; // XOR mask to flip the case of a letter. diff --git a/src/System.Private.CoreLib/shared/System/Collections/ArrayList.cs b/src/System.Private.CoreLib/shared/System/Collections/ArrayList.cs index d4ae3da5350d..52bc99fb20b3 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/ArrayList.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/ArrayList.cs @@ -983,8 +983,7 @@ public override void InsertRange(int index, ICollection c) if (c.Count > 0) { - ArrayList? al = _list as ArrayList; - if (al != null) + if (_list is ArrayList al) { // We need to special case ArrayList. // When c is a range of _list, we need to handle this in a special way. diff --git a/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs b/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs index e8f431be6db3..102d2c9f8b64 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs @@ -58,8 +58,7 @@ public int Compare(object? a, object? b) if (a == null) return -1; if (b == null) return 1; - string? sa = a as string; - if (sa != null && b is string sb) + if (a is string sa && b is string sb) return _compareInfo.Compare(sa, sb); if (a is IComparable ia) diff --git a/src/System.Private.CoreLib/shared/System/Convert.cs b/src/System.Private.CoreLib/shared/System/Convert.cs index 8616cd946058..e9c230c2022b 100644 --- a/src/System.Private.CoreLib/shared/System/Convert.cs +++ b/src/System.Private.CoreLib/shared/System/Convert.cs @@ -208,47 +208,28 @@ public static bool IsDBNull(object? value) // This line is invalid for things like Enums that return a TypeCode // of int, but the object can't actually be cast to an int. // if (v.GetTypeCode() == typeCode) return value; - switch (typeCode) + return typeCode switch { - case TypeCode.Boolean: - return v.ToBoolean(provider); - case TypeCode.Char: - return v.ToChar(provider); - case TypeCode.SByte: - return v.ToSByte(provider); - case TypeCode.Byte: - return v.ToByte(provider); - case TypeCode.Int16: - return v.ToInt16(provider); - case TypeCode.UInt16: - return v.ToUInt16(provider); - case TypeCode.Int32: - return v.ToInt32(provider); - case TypeCode.UInt32: - return v.ToUInt32(provider); - case TypeCode.Int64: - return v.ToInt64(provider); - case TypeCode.UInt64: - return v.ToUInt64(provider); - case TypeCode.Single: - return v.ToSingle(provider); - case TypeCode.Double: - return v.ToDouble(provider); - case TypeCode.Decimal: - return v.ToDecimal(provider); - case TypeCode.DateTime: - return v.ToDateTime(provider); - case TypeCode.String: - return v.ToString(provider); - case TypeCode.Object: - return value; - case TypeCode.DBNull: - throw new InvalidCastException(SR.InvalidCast_DBNull); - case TypeCode.Empty: - throw new InvalidCastException(SR.InvalidCast_Empty); - default: - throw new ArgumentException(SR.Arg_UnknownTypeCode); - } + TypeCode.Boolean => v.ToBoolean(provider), + TypeCode.Char => v.ToChar(provider), + TypeCode.SByte => v.ToSByte(provider), + TypeCode.Byte => v.ToByte(provider), + TypeCode.Int16 => v.ToInt16(provider), + TypeCode.UInt16 => v.ToUInt16(provider), + TypeCode.Int32 => v.ToInt32(provider), + TypeCode.UInt32 => v.ToUInt32(provider), + TypeCode.Int64 => v.ToInt64(provider), + TypeCode.UInt64 => v.ToUInt64(provider), + TypeCode.Single => v.ToSingle(provider), + TypeCode.Double => v.ToDouble(provider), + TypeCode.Decimal => v.ToDecimal(provider), + TypeCode.DateTime => v.ToDateTime(provider), + TypeCode.String => v.ToString(provider), + TypeCode.Object => value, + TypeCode.DBNull => throw new InvalidCastException(SR.InvalidCast_DBNull), + TypeCode.Empty => throw new InvalidCastException(SR.InvalidCast_Empty), + _ => throw new ArgumentException(SR.Arg_UnknownTypeCode), + }; } internal static object DefaultToType(IConvertible value, Type targetType, IFormatProvider? provider) diff --git a/src/System.Private.CoreLib/shared/System/DateTime.Windows.cs b/src/System.Private.CoreLib/shared/System/DateTime.Windows.cs index 468c3691ccd5..ebfed3c99e86 100644 --- a/src/System.Private.CoreLib/shared/System/DateTime.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/DateTime.Windows.cs @@ -31,13 +31,12 @@ internal static unsafe bool IsValidTimeWithLeapSeconds(int year, int month, int DateTime dt = new DateTime(year, month, day); FullSystemTime time = new FullSystemTime(year, month, dt.DayOfWeek, day, hour, minute, second); - switch (kind) + return kind switch { - case DateTimeKind.Local: return ValidateSystemTime(&time.systemTime, localTime: true); - case DateTimeKind.Utc: return ValidateSystemTime(&time.systemTime, localTime: false); - default: - return ValidateSystemTime(&time.systemTime, localTime: true) || ValidateSystemTime(&time.systemTime, localTime: false); - } + DateTimeKind.Local => ValidateSystemTime(&time.systemTime, localTime: true), + DateTimeKind.Utc => ValidateSystemTime(&time.systemTime, localTime: false), + _ => ValidateSystemTime(&time.systemTime, localTime: true) || ValidateSystemTime(&time.systemTime, localTime: false), + }; } private static unsafe DateTime FromFileTimeLeapSecondsAware(long fileTime) diff --git a/src/System.Private.CoreLib/shared/System/DateTime.cs b/src/System.Private.CoreLib/shared/System/DateTime.cs index 4bdbaf077caf..6cb1c1ecfc8a 100644 --- a/src/System.Private.CoreLib/shared/System/DateTime.cs +++ b/src/System.Private.CoreLib/shared/System/DateTime.cs @@ -1061,15 +1061,12 @@ public DateTimeKind Kind { get { - switch (InternalKind) + return InternalKind switch { - case KindUnspecified: - return DateTimeKind.Unspecified; - case KindUtc: - return DateTimeKind.Utc; - default: - return DateTimeKind.Local; - } + KindUnspecified => DateTimeKind.Unspecified, + KindUtc => DateTimeKind.Utc, + _ => DateTimeKind.Local, + }; } } diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventProvider.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventProvider.cs index 8460b8b2a314..4b22fc0c9a7c 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventProvider.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventProvider.cs @@ -134,25 +134,15 @@ public enum WriteEventErrorCode : int // EventSource has special logic to do this, no one else should be calling EventProvider. internal EventProvider(EventProviderType providerType) { - switch (providerType) + m_eventProvider = providerType switch { - case EventProviderType.ETW: #if PLATFORM_WINDOWS - m_eventProvider = new EtwEventProvider(); -#else - m_eventProvider = new NoOpEventProvider(); + EventProviderType.ETW => new EtwEventProvider(), #endif - break; - case EventProviderType.EventPipe: #if FEATURE_PERFTRACING - m_eventProvider = new EventPipeEventProvider(); -#else - m_eventProvider = new NoOpEventProvider(); + EventProviderType.EventPipe => new EventPipeEventProvider(), #endif - break; - default: - m_eventProvider = new NoOpEventProvider(); - break; + _ => new NoOpEventProvider(), }; } diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/Statics.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/Statics.cs index 0131a00237ec..e32b3b827222 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/Statics.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/Statics.cs @@ -203,25 +203,18 @@ public static TraceLoggingDataType Format8( EventFieldFormat format, TraceLoggingDataType native) { - switch (format) + return format switch { - case EventFieldFormat.Default: - return native; - case EventFieldFormat.String: - return TraceLoggingDataType.Char8; - case EventFieldFormat.Boolean: - return TraceLoggingDataType.Boolean8; - case EventFieldFormat.Hexadecimal: - return TraceLoggingDataType.HexInt8; + EventFieldFormat.Default => native, + EventFieldFormat.String => TraceLoggingDataType.Char8, + EventFieldFormat.Boolean => TraceLoggingDataType.Boolean8, + EventFieldFormat.Hexadecimal => TraceLoggingDataType.HexInt8, #if false - case EventSourceFieldFormat.Signed: - return TraceLoggingDataType.Int8; - case EventSourceFieldFormat.Unsigned: - return TraceLoggingDataType.UInt8; + EventSourceFieldFormat.Signed => TraceLoggingDataType.Int8, + EventSourceFieldFormat.Unsigned => TraceLoggingDataType.UInt8, #endif - default: - return MakeDataType(native, format); - } + _ => MakeDataType(native, format), + }; } /// @@ -234,25 +227,18 @@ public static TraceLoggingDataType Format16( EventFieldFormat format, TraceLoggingDataType native) { - switch (format) + return format switch { - case EventFieldFormat.Default: - return native; - case EventFieldFormat.String: - return TraceLoggingDataType.Char16; - case EventFieldFormat.Hexadecimal: - return TraceLoggingDataType.HexInt16; + EventFieldFormat.Default => native, + EventFieldFormat.String => TraceLoggingDataType.Char16, + EventFieldFormat.Hexadecimal => TraceLoggingDataType.HexInt16, #if false - case EventSourceFieldFormat.Port: - return TraceLoggingDataType.Port; - case EventSourceFieldFormat.Signed: - return TraceLoggingDataType.Int16; - case EventSourceFieldFormat.Unsigned: - return TraceLoggingDataType.UInt16; + EventSourceFieldFormat.Port => TraceLoggingDataType.Port, + EventSourceFieldFormat.Signed => TraceLoggingDataType.Int16, + EventSourceFieldFormat.Unsigned => TraceLoggingDataType.UInt16, #endif - default: - return MakeDataType(native, format); - } + _ => MakeDataType(native, format), + }; } /// @@ -265,37 +251,27 @@ public static TraceLoggingDataType Format32( EventFieldFormat format, TraceLoggingDataType native) { - switch (format) + return format switch { - case EventFieldFormat.Default: - return native; - case EventFieldFormat.Boolean: - return TraceLoggingDataType.Boolean32; - case EventFieldFormat.Hexadecimal: - return TraceLoggingDataType.HexInt32; + EventFieldFormat.Default => native, + EventFieldFormat.Boolean => TraceLoggingDataType.Boolean32, + EventFieldFormat.Hexadecimal => TraceLoggingDataType.HexInt32, #if false - case EventSourceFieldFormat.Ipv4Address: - return TraceLoggingDataType.Ipv4Address; - case EventSourceFieldFormat.ProcessId: - return TraceLoggingDataType.ProcessId; - case EventSourceFieldFormat.ThreadId: - return TraceLoggingDataType.ThreadId; - case EventSourceFieldFormat.Win32Error: - return TraceLoggingDataType.Win32Error; - case EventSourceFieldFormat.NTStatus: - return TraceLoggingDataType.NTStatus; + EventSourceFieldFormat.Ipv4Address => TraceLoggingDataType.Ipv4Address, + EventSourceFieldFormat.ProcessId => TraceLoggingDataType.ProcessId, + EventSourceFieldFormat.ThreadId => TraceLoggingDataType.ThreadId, + EventSourceFieldFormat.Win32Error => TraceLoggingDataType.Win32Error, + EventSourceFieldFormat.NTStatus => TraceLoggingDataType.NTStatus, #endif - case EventFieldFormat.HResult: - return TraceLoggingDataType.HResult; + EventFieldFormat.HResult => TraceLoggingDataType.HResult, #if false case EventSourceFieldFormat.Signed: return TraceLoggingDataType.Int32; case EventSourceFieldFormat.Unsigned: return TraceLoggingDataType.UInt32; #endif - default: - return MakeDataType(native, format); - } + _ => MakeDataType(native, format), + }; } /// @@ -308,23 +284,17 @@ public static TraceLoggingDataType Format64( EventFieldFormat format, TraceLoggingDataType native) { - switch (format) + return format switch { - case EventFieldFormat.Default: - return native; - case EventFieldFormat.Hexadecimal: - return TraceLoggingDataType.HexInt64; + EventFieldFormat.Default => native, + EventFieldFormat.Hexadecimal => TraceLoggingDataType.HexInt64, #if false - case EventSourceFieldFormat.FileTime: - return TraceLoggingDataType.FileTime; - case EventSourceFieldFormat.Signed: - return TraceLoggingDataType.Int64; - case EventSourceFieldFormat.Unsigned: - return TraceLoggingDataType.UInt64; + EventSourceFieldFormat.FileTime => TraceLoggingDataType.FileTime, + EventSourceFieldFormat.Signed => TraceLoggingDataType.Int64, + EventSourceFieldFormat.Unsigned => TraceLoggingDataType.UInt64, #endif - default: - return MakeDataType(native, format); - } + _ => MakeDataType(native, format), + }; } /// @@ -337,21 +307,16 @@ public static TraceLoggingDataType FormatPtr( EventFieldFormat format, TraceLoggingDataType native) { - switch (format) + return format switch { - case EventFieldFormat.Default: - return native; - case EventFieldFormat.Hexadecimal: - return HexIntPtrType; + EventFieldFormat.Default => native, + EventFieldFormat.Hexadecimal => HexIntPtrType, #if false - case EventSourceFieldFormat.Signed: - return IntPtrType; - case EventSourceFieldFormat.Unsigned: - return UIntPtrType; + EventSourceFieldFormat.Signed => IntPtrType, + EventSourceFieldFormat.Unsigned => UIntPtrType, #endif - default: - return MakeDataType(native, format); - } + _ => MakeDataType(native, format), + }; } #endregion diff --git a/src/System.Private.CoreLib/shared/System/Enum.cs b/src/System.Private.CoreLib/shared/System/Enum.cs index df7c1eeadd8d..206b1e3fd517 100644 --- a/src/System.Private.CoreLib/shared/System/Enum.cs +++ b/src/System.Private.CoreLib/shared/System/Enum.cs @@ -42,39 +42,24 @@ public abstract partial class Enum : ValueType, IComparable, IFormattable, IConv private string ValueToString() { ref byte data = ref this.GetRawData(); - switch (InternalGetCorElementType()) + return (InternalGetCorElementType()) switch { - case CorElementType.ELEMENT_TYPE_I1: - return Unsafe.As(ref data).ToString(); - case CorElementType.ELEMENT_TYPE_U1: - return data.ToString(); - case CorElementType.ELEMENT_TYPE_BOOLEAN: - return Unsafe.As(ref data).ToString(); - case CorElementType.ELEMENT_TYPE_I2: - return Unsafe.As(ref data).ToString(); - case CorElementType.ELEMENT_TYPE_U2: - return Unsafe.As(ref data).ToString(); - case CorElementType.ELEMENT_TYPE_CHAR: - return Unsafe.As(ref data).ToString(); - case CorElementType.ELEMENT_TYPE_I4: - return Unsafe.As(ref data).ToString(); - case CorElementType.ELEMENT_TYPE_U4: - return Unsafe.As(ref data).ToString(); - case CorElementType.ELEMENT_TYPE_R4: - return Unsafe.As(ref data).ToString(); - case CorElementType.ELEMENT_TYPE_I8: - return Unsafe.As(ref data).ToString(); - case CorElementType.ELEMENT_TYPE_U8: - return Unsafe.As(ref data).ToString(); - case CorElementType.ELEMENT_TYPE_R8: - return Unsafe.As(ref data).ToString(); - case CorElementType.ELEMENT_TYPE_I: - return Unsafe.As(ref data).ToString(); - case CorElementType.ELEMENT_TYPE_U: - return Unsafe.As(ref data).ToString(); - default: - throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); - } + CorElementType.ELEMENT_TYPE_I1 => Unsafe.As(ref data).ToString(), + CorElementType.ELEMENT_TYPE_U1 => data.ToString(), + CorElementType.ELEMENT_TYPE_BOOLEAN => Unsafe.As(ref data).ToString(), + CorElementType.ELEMENT_TYPE_I2 => Unsafe.As(ref data).ToString(), + CorElementType.ELEMENT_TYPE_U2 => Unsafe.As(ref data).ToString(), + CorElementType.ELEMENT_TYPE_CHAR => Unsafe.As(ref data).ToString(), + CorElementType.ELEMENT_TYPE_I4 => Unsafe.As(ref data).ToString(), + CorElementType.ELEMENT_TYPE_U4 => Unsafe.As(ref data).ToString(), + CorElementType.ELEMENT_TYPE_R4 => Unsafe.As(ref data).ToString(), + CorElementType.ELEMENT_TYPE_I8 => Unsafe.As(ref data).ToString(), + CorElementType.ELEMENT_TYPE_U8 => Unsafe.As(ref data).ToString(), + CorElementType.ELEMENT_TYPE_R8 => Unsafe.As(ref data).ToString(), + CorElementType.ELEMENT_TYPE_I => Unsafe.As(ref data).ToString(), + CorElementType.ELEMENT_TYPE_U => Unsafe.As(ref data).ToString(), + _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType), + }; } private string ValueToHexString() @@ -104,33 +89,20 @@ private string ValueToHexString() private static string ValueToHexString(object value) { - switch (Convert.GetTypeCode(value)) + return (Convert.GetTypeCode(value)) switch { - case TypeCode.SByte: - return ((byte)(sbyte)value).ToString("X2", null); - case TypeCode.Byte: - return ((byte)value).ToString("X2", null); - case TypeCode.Boolean: - // direct cast from bool to byte is not allowed - return Convert.ToByte((bool)value).ToString("X2", null); - case TypeCode.Int16: - return ((ushort)(short)value).ToString("X4", null); - case TypeCode.UInt16: - return ((ushort)value).ToString("X4", null); - case TypeCode.Char: - return ((ushort)(char)value).ToString("X4", null); - case TypeCode.UInt32: - return ((uint)value).ToString("X8", null); - case TypeCode.Int32: - return ((uint)(int)value).ToString("X8", null); - case TypeCode.UInt64: - return ((ulong)value).ToString("X16", null); - case TypeCode.Int64: - return ((ulong)(long)value).ToString("X16", null); - // All unsigned types will be directly cast - default: - throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); - } + TypeCode.SByte => ((byte)(sbyte)value).ToString("X2", null), + TypeCode.Byte => ((byte)value).ToString("X2", null), + TypeCode.Boolean => Convert.ToByte((bool)value).ToString("X2", null), // direct cast from bool to byte is not allowed + TypeCode.Int16 => ((ushort)(short)value).ToString("X4", null), + TypeCode.UInt16 => ((ushort)value).ToString("X4", null), + TypeCode.Char => ((ushort)(char)value).ToString("X4", null), + TypeCode.UInt32 => ((uint)value).ToString("X8", null), + TypeCode.Int32 => ((uint)(int)value).ToString("X8", null), + TypeCode.UInt64 => ((ulong)value).ToString("X16", null), + TypeCode.Int64 => ((ulong)(long)value).ToString("X16", null), + _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType), + }; } internal static string? GetEnumName(RuntimeType enumType, ulong ulValue) @@ -271,46 +243,20 @@ internal static ulong ToUInt64(object value) // Helper function to silently convert the value to UInt64 from the other base types for enum without throwing an exception. // This is need since the Convert functions do overflow checks. TypeCode typeCode = Convert.GetTypeCode(value); - - ulong result; - switch (typeCode) + var result = typeCode switch { - case TypeCode.SByte: - result = (ulong)(sbyte)value; - break; - case TypeCode.Byte: - result = (byte)value; - break; - case TypeCode.Boolean: - // direct cast from bool to byte is not allowed - result = Convert.ToByte((bool)value); - break; - case TypeCode.Int16: - result = (ulong)(short)value; - break; - case TypeCode.UInt16: - result = (ushort)value; - break; - case TypeCode.Char: - result = (ushort)(char)value; - break; - case TypeCode.UInt32: - result = (uint)value; - break; - case TypeCode.Int32: - result = (ulong)(int)value; - break; - case TypeCode.UInt64: - result = (ulong)value; - break; - case TypeCode.Int64: - result = (ulong)(long)value; - break; - // All unsigned types will be directly cast - default: - throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); - } - + TypeCode.SByte => (ulong)(sbyte)value, + TypeCode.Byte => (byte)value, + TypeCode.Boolean => Convert.ToByte((bool)value), // direct cast from bool to byte is not allowed + TypeCode.Int16 => (ulong)(short)value, + TypeCode.UInt16 => (ushort)value, + TypeCode.Char => (ushort)(char)value, + TypeCode.UInt32 => (uint)value, + TypeCode.Int32 => (ulong)(int)value, + TypeCode.UInt64 => (ulong)value, + TypeCode.Int64 => (ulong)(long)value, + _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType), + }; return result; } @@ -786,42 +732,20 @@ public static object ToObject(Type enumType, object value) // Delegate rest of error checking to the other functions TypeCode typeCode = Convert.GetTypeCode(value); - switch (typeCode) + return typeCode switch { - case TypeCode.Int32: - return ToObject(enumType, (int)value); - - case TypeCode.SByte: - return ToObject(enumType, (sbyte)value); - - case TypeCode.Int16: - return ToObject(enumType, (short)value); - - case TypeCode.Int64: - return ToObject(enumType, (long)value); - - case TypeCode.UInt32: - return ToObject(enumType, (uint)value); - - case TypeCode.Byte: - return ToObject(enumType, (byte)value); - - case TypeCode.UInt16: - return ToObject(enumType, (ushort)value); - - case TypeCode.UInt64: - return ToObject(enumType, (ulong)value); - - case TypeCode.Char: - return ToObject(enumType, (char)value); - - case TypeCode.Boolean: - return ToObject(enumType, (bool)value); - - default: - // All unsigned types will be directly cast - throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, nameof(value)); - } + TypeCode.Int32 => ToObject(enumType, (int)value), + TypeCode.SByte => ToObject(enumType, (sbyte)value), + TypeCode.Int16 => ToObject(enumType, (short)value), + TypeCode.Int64 => ToObject(enumType, (long)value), + TypeCode.UInt32 => ToObject(enumType, (uint)value), + TypeCode.Byte => ToObject(enumType, (byte)value), + TypeCode.UInt16 => ToObject(enumType, (ushort)value), + TypeCode.UInt64 => ToObject(enumType, (ulong)value), + TypeCode.Char => ToObject(enumType, (char)value), + TypeCode.Boolean => ToObject(enumType, (bool)value), + _ => throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, nameof(value)), + }; } public static string Format(Type enumType, object value, string format) @@ -886,39 +810,24 @@ public static string Format(Type enumType, object value, string format) internal object GetValue() { ref byte data = ref this.GetRawData(); - switch (InternalGetCorElementType()) + return (InternalGetCorElementType()) switch { - case CorElementType.ELEMENT_TYPE_I1: - return Unsafe.As(ref data); - case CorElementType.ELEMENT_TYPE_U1: - return data; - case CorElementType.ELEMENT_TYPE_BOOLEAN: - return Unsafe.As(ref data); - case CorElementType.ELEMENT_TYPE_I2: - return Unsafe.As(ref data); - case CorElementType.ELEMENT_TYPE_U2: - return Unsafe.As(ref data); - case CorElementType.ELEMENT_TYPE_CHAR: - return Unsafe.As(ref data); - case CorElementType.ELEMENT_TYPE_I4: - return Unsafe.As(ref data); - case CorElementType.ELEMENT_TYPE_U4: - return Unsafe.As(ref data); - case CorElementType.ELEMENT_TYPE_R4: - return Unsafe.As(ref data); - case CorElementType.ELEMENT_TYPE_I8: - return Unsafe.As(ref data); - case CorElementType.ELEMENT_TYPE_U8: - return Unsafe.As(ref data); - case CorElementType.ELEMENT_TYPE_R8: - return Unsafe.As(ref data); - case CorElementType.ELEMENT_TYPE_I: - return Unsafe.As(ref data); - case CorElementType.ELEMENT_TYPE_U: - return Unsafe.As(ref data); - default: - throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); - } + CorElementType.ELEMENT_TYPE_I1 => Unsafe.As(ref data), + CorElementType.ELEMENT_TYPE_U1 => data, + CorElementType.ELEMENT_TYPE_BOOLEAN => Unsafe.As(ref data), + CorElementType.ELEMENT_TYPE_I2 => Unsafe.As(ref data), + CorElementType.ELEMENT_TYPE_U2 => Unsafe.As(ref data), + CorElementType.ELEMENT_TYPE_CHAR => Unsafe.As(ref data), + CorElementType.ELEMENT_TYPE_I4 => Unsafe.As(ref data), + CorElementType.ELEMENT_TYPE_U4 => Unsafe.As(ref data), + CorElementType.ELEMENT_TYPE_R4 => Unsafe.As(ref data), + CorElementType.ELEMENT_TYPE_I8 => Unsafe.As(ref data), + CorElementType.ELEMENT_TYPE_U8 => Unsafe.As(ref data), + CorElementType.ELEMENT_TYPE_R8 => Unsafe.As(ref data), + CorElementType.ELEMENT_TYPE_I => Unsafe.As(ref data), + CorElementType.ELEMENT_TYPE_U => Unsafe.As(ref data), + _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType), + }; } private ulong ToUInt64() @@ -966,39 +875,24 @@ public override int GetHashCode() // The runtime can bypass calls to Enum::GetHashCode and call the underlying type's GetHashCode directly // to avoid boxing the enum. ref byte data = ref this.GetRawData(); - switch (InternalGetCorElementType()) + return (InternalGetCorElementType()) switch { - case CorElementType.ELEMENT_TYPE_I1: - return Unsafe.As(ref data).GetHashCode(); - case CorElementType.ELEMENT_TYPE_U1: - return data.GetHashCode(); - case CorElementType.ELEMENT_TYPE_BOOLEAN: - return Unsafe.As(ref data).GetHashCode(); - case CorElementType.ELEMENT_TYPE_I2: - return Unsafe.As(ref data).GetHashCode(); - case CorElementType.ELEMENT_TYPE_U2: - return Unsafe.As(ref data).GetHashCode(); - case CorElementType.ELEMENT_TYPE_CHAR: - return Unsafe.As(ref data).GetHashCode(); - case CorElementType.ELEMENT_TYPE_I4: - return Unsafe.As(ref data).GetHashCode(); - case CorElementType.ELEMENT_TYPE_U4: - return Unsafe.As(ref data).GetHashCode(); - case CorElementType.ELEMENT_TYPE_R4: - return Unsafe.As(ref data).GetHashCode(); - case CorElementType.ELEMENT_TYPE_I8: - return Unsafe.As(ref data).GetHashCode(); - case CorElementType.ELEMENT_TYPE_U8: - return Unsafe.As(ref data).GetHashCode(); - case CorElementType.ELEMENT_TYPE_R8: - return Unsafe.As(ref data).GetHashCode(); - case CorElementType.ELEMENT_TYPE_I: - return Unsafe.As(ref data).GetHashCode(); - case CorElementType.ELEMENT_TYPE_U: - return Unsafe.As(ref data).GetHashCode(); - default: - throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); - } + CorElementType.ELEMENT_TYPE_I1 => Unsafe.As(ref data).GetHashCode(), + CorElementType.ELEMENT_TYPE_U1 => data.GetHashCode(), + CorElementType.ELEMENT_TYPE_BOOLEAN => Unsafe.As(ref data).GetHashCode(), + CorElementType.ELEMENT_TYPE_I2 => Unsafe.As(ref data).GetHashCode(), + CorElementType.ELEMENT_TYPE_U2 => Unsafe.As(ref data).GetHashCode(), + CorElementType.ELEMENT_TYPE_CHAR => Unsafe.As(ref data).GetHashCode(), + CorElementType.ELEMENT_TYPE_I4 => Unsafe.As(ref data).GetHashCode(), + CorElementType.ELEMENT_TYPE_U4 => Unsafe.As(ref data).GetHashCode(), + CorElementType.ELEMENT_TYPE_R4 => Unsafe.As(ref data).GetHashCode(), + CorElementType.ELEMENT_TYPE_I8 => Unsafe.As(ref data).GetHashCode(), + CorElementType.ELEMENT_TYPE_U8 => Unsafe.As(ref data).GetHashCode(), + CorElementType.ELEMENT_TYPE_R8 => Unsafe.As(ref data).GetHashCode(), + CorElementType.ELEMENT_TYPE_I => Unsafe.As(ref data).GetHashCode(), + CorElementType.ELEMENT_TYPE_U => Unsafe.As(ref data).GetHashCode(), + _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType), + }; } public override string ToString() @@ -1066,31 +960,20 @@ public string ToString(IFormatProvider? provider) #region IConvertible public TypeCode GetTypeCode() { - switch (InternalGetCorElementType()) + return (InternalGetCorElementType()) switch { - case CorElementType.ELEMENT_TYPE_I1: - return TypeCode.SByte; - case CorElementType.ELEMENT_TYPE_U1: - return TypeCode.Byte; - case CorElementType.ELEMENT_TYPE_BOOLEAN: - return TypeCode.Boolean; - case CorElementType.ELEMENT_TYPE_I2: - return TypeCode.Int16; - case CorElementType.ELEMENT_TYPE_U2: - return TypeCode.UInt16; - case CorElementType.ELEMENT_TYPE_CHAR: - return TypeCode.Char; - case CorElementType.ELEMENT_TYPE_I4: - return TypeCode.Int32; - case CorElementType.ELEMENT_TYPE_U4: - return TypeCode.UInt32; - case CorElementType.ELEMENT_TYPE_I8: - return TypeCode.Int64; - case CorElementType.ELEMENT_TYPE_U8: - return TypeCode.UInt64; - default: - throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); - } + CorElementType.ELEMENT_TYPE_I1 => TypeCode.SByte, + CorElementType.ELEMENT_TYPE_U1 => TypeCode.Byte, + CorElementType.ELEMENT_TYPE_BOOLEAN => TypeCode.Boolean, + CorElementType.ELEMENT_TYPE_I2 => TypeCode.Int16, + CorElementType.ELEMENT_TYPE_U2 => TypeCode.UInt16, + CorElementType.ELEMENT_TYPE_CHAR => TypeCode.Char, + CorElementType.ELEMENT_TYPE_I4 => TypeCode.Int32, + CorElementType.ELEMENT_TYPE_U4 => TypeCode.UInt32, + CorElementType.ELEMENT_TYPE_I8 => TypeCode.Int64, + CorElementType.ELEMENT_TYPE_U8 => TypeCode.UInt64, + _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType), + }; } bool IConvertible.ToBoolean(IFormatProvider? provider) diff --git a/src/System.Private.CoreLib/shared/System/Environment.cs b/src/System.Private.CoreLib/shared/System/Environment.cs index 2b638fde9eb3..0f602030c528 100644 --- a/src/System.Private.CoreLib/shared/System/Environment.cs +++ b/src/System.Private.CoreLib/shared/System/Environment.cs @@ -162,8 +162,7 @@ public static long WorkingSet // present in Process. If it proves important, we could look at separating that functionality out of Process into // Common files which could also be included here. Type? processType = Type.GetType("System.Diagnostics.Process, System.Diagnostics.Process, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false); - IDisposable? currentProcess = processType?.GetMethod("GetCurrentProcess")?.Invoke(null, BindingFlags.DoNotWrapExceptions, null, null, null) as IDisposable; - if (currentProcess != null) + if (processType?.GetMethod("GetCurrentProcess")?.Invoke(null, BindingFlags.DoNotWrapExceptions, null, null, null) is IDisposable currentProcess) { using (currentProcess) { diff --git a/src/System.Private.CoreLib/shared/System/Globalization/Calendar.cs b/src/System.Private.CoreLib/shared/System/Globalization/Calendar.cs index 4460d3d06a22..86e630180c34 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/Calendar.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/Calendar.cs @@ -520,19 +520,17 @@ public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek, SR.Format(SR.ArgumentOutOfRange_Range, DayOfWeek.Sunday, DayOfWeek.Saturday)); } - switch (rule) + + return rule switch { - case CalendarWeekRule.FirstDay: - return GetFirstDayWeekOfYear(time, (int)firstDayOfWeek); - case CalendarWeekRule.FirstFullWeek: - return GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7); - case CalendarWeekRule.FirstFourDayWeek: - return GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4); - default: - throw new ArgumentOutOfRangeException( + CalendarWeekRule.FirstDay => GetFirstDayWeekOfYear(time, (int)firstDayOfWeek), + CalendarWeekRule.FirstFullWeek => GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7), + CalendarWeekRule.FirstFourDayWeek => GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4), + _ => throw new ArgumentOutOfRangeException( nameof(rule), rule, - SR.Format(SR.ArgumentOutOfRange_Range, CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek)); } + SR.Format(SR.ArgumentOutOfRange_Range, CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek)), + }; } /// diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CultureInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/CultureInfo.cs index 63dd62c7053e..76ddc4c69330 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CultureInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CultureInfo.cs @@ -649,15 +649,12 @@ public string IetfLanguageTag get { // special case the compatibility cultures - switch (this.Name) + return Name switch { - case "zh-CHT": - return "zh-Hant"; - case "zh-CHS": - return "zh-Hans"; - default: - return this.Name; - } + "zh-CHT" => "zh-Hant", + "zh-CHS" => "zh-Hans", + _ => Name, + }; } } diff --git a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs index 67a7b47c5e89..07327ff902d8 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs @@ -1316,19 +1316,12 @@ public string[] MonthNames /// internal string InternalGetMonthName(int month, MonthNameStyles style, bool abbreviated) { - string[] monthNamesArray; - switch (style) + string[] monthNamesArray = style switch { - case MonthNameStyles.Genitive: - monthNamesArray = InternalGetGenitiveMonthNames(abbreviated); - break; - case MonthNameStyles.LeapYear: - monthNamesArray = InternalGetLeapYearMonthNames(); - break; - default: - monthNamesArray = (abbreviated ? InternalGetAbbreviatedMonthNames() : InternalGetMonthNames()); - break; - } + MonthNameStyles.Genitive => InternalGetGenitiveMonthNames(abbreviated), + MonthNameStyles.LeapYear => InternalGetLeapYearMonthNames(), + _ => (abbreviated ? InternalGetAbbreviatedMonthNames() : InternalGetMonthNames()), + }; // The month range is from 1 ~ m_monthNames.Length // (actually is 13 right now for all cases) diff --git a/src/System.Private.CoreLib/shared/System/Globalization/HebrewCalendar.cs b/src/System.Private.CoreLib/shared/System/Globalization/HebrewCalendar.cs index d72e3817b19f..667721dc1627 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/HebrewCalendar.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/HebrewCalendar.cs @@ -363,17 +363,13 @@ private static void CheckTicksRange(long ticks) private static int GetResult(DateBuffer result, int part) { - switch (part) + return part switch { - case DatePartYear: - return result.year; - case DatePartMonth: - return result.month; - case DatePartDay: - return result.day; - } - - throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing); + DatePartYear => result.year, + DatePartMonth => result.month, + DatePartDay => result.day, + _ => throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing), + }; } /// diff --git a/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs b/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs index 7dfac05aaddc..4f492b755efb 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs @@ -568,18 +568,18 @@ internal bool SetBadFormatSpecifierFailure(char? formatSpecifierCharacter = null internal static long Pow10(int pow) { - switch (pow) - { - case 0: return 1; - case 1: return 10; - case 2: return 100; - case 3: return 1000; - case 4: return 10000; - case 5: return 100000; - case 6: return 1000000; - case 7: return 10000000; - default: return (long)Math.Pow(10, pow); - } + return pow switch + { + 0 => 1, + 1 => 10, + 2 => 100, + 3 => 1000, + 4 => 10000, + 5 => 100000, + 6 => 1000000, + 7 => 10000000, + _ => (long)Math.Pow(10, pow), + }; } private static bool TryTimeToTicks(bool positive, TimeSpanToken days, TimeSpanToken hours, TimeSpanToken minutes, TimeSpanToken seconds, TimeSpanToken fraction, out long result) @@ -740,15 +740,15 @@ private static bool ProcessTerminalState(ref TimeSpanRawInfo raw, TimeSpanStanda } } - switch (raw._numCount) + return raw._numCount switch { - case 1: return ProcessTerminal_D(ref raw, style, ref result); - case 2: return ProcessTerminal_HM(ref raw, style, ref result); - case 3: return ProcessTerminal_HM_S_D(ref raw, style, ref result); - case 4: return ProcessTerminal_HMS_F_D(ref raw, style, ref result); - case 5: return ProcessTerminal_DHMSF(ref raw, style, ref result); - default: return result.SetBadTimeSpanFailure(); - } + 1 => ProcessTerminal_D(ref raw, style, ref result), + 2 => ProcessTerminal_HM(ref raw, style, ref result), + 3 => ProcessTerminal_HM_S_D(ref raw, style, ref result), + 4 => ProcessTerminal_HMS_F_D(ref raw, style, ref result), + 5 => ProcessTerminal_DHMSF(ref raw, style, ref result), + _ => result.SetBadTimeSpanFailure(), + }; } /// Validate the 5-number "Days.Hours:Minutes:Seconds.Fraction" terminal case. diff --git a/src/System.Private.CoreLib/shared/System/Guid.cs b/src/System.Private.CoreLib/shared/System/Guid.cs index ba92c19381cc..1a9aee78a566 100644 --- a/src/System.Private.CoreLib/shared/System/Guid.cs +++ b/src/System.Private.CoreLib/shared/System/Guid.cs @@ -238,33 +238,15 @@ public static Guid ParseExact(ReadOnlySpan input, ReadOnlySpan forma input = input.Trim(); var result = new GuidResult(GuidParseThrowStyle.AllButOverflow); - bool success; - switch ((char)(format[0] | 0x20)) - { - case 'd': - success = TryParseExactD(input, ref result); - break; - - case 'n': - success = TryParseExactN(input, ref result); - break; - - case 'b': - success = TryParseExactB(input, ref result); - break; - - case 'p': - success = TryParseExactP(input, ref result); - break; - - case 'x': - success = TryParseExactX(input, ref result); - break; - - default: - throw new FormatException(SR.Format_InvalidGuidFormatSpecification); - } - + bool success = ((char)(format[0] | 0x20)) switch + { + 'd' => TryParseExactD(input, ref result), + 'n' => TryParseExactN(input, ref result), + 'b' => TryParseExactB(input, ref result), + 'p' => TryParseExactP(input, ref result), + 'x' => TryParseExactX(input, ref result), + _ => throw new FormatException(SR.Format_InvalidGuidFormatSpecification), + }; Debug.Assert(success, "GuidParseThrowStyle.AllButOverflow means throw on all failures"); return result._parsedGuid; } @@ -337,21 +319,16 @@ private static bool TryParseGuid(ReadOnlySpan guidString, ref GuidResult r return false; } - switch (guidString[0]) + return (guidString[0]) switch { - case '(': - return TryParseExactP(guidString, ref result); - - case '{': - return guidString.Contains('-') ? + '(' => TryParseExactP(guidString, ref result), + '{' => guidString.Contains('-') ? TryParseExactB(guidString, ref result) : - TryParseExactX(guidString, ref result); - - default: - return guidString.Contains('-') ? + TryParseExactX(guidString, ref result), + _ => guidString.Contains('-') ? TryParseExactD(guidString, ref result) : - TryParseExactN(guidString, ref result); - } + TryParseExactN(guidString, ref result), + }; } // Two helpers used for parsing components: diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx2.cs b/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx2.cs index 3a066bb38ccd..f3e5877447db 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx2.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx2.cs @@ -848,19 +848,14 @@ internal Avx2() { } /// public static unsafe Vector128 GatherVector128(int* baseAddress, Vector128 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector128(baseAddress, index, 1); - case 2: - return GatherVector128(baseAddress, index, 2); - case 4: - return GatherVector128(baseAddress, index, 4); - case 8: - return GatherVector128(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector128(baseAddress, index, 1), + 2 => GatherVector128(baseAddress, index, 2), + 4 => GatherVector128(baseAddress, index, 4), + 8 => GatherVector128(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128i _mm_i32gather_epi32 (int const* base_addr, __m128i vindex, const int scale) @@ -869,19 +864,14 @@ public static unsafe Vector128 GatherVector128(int* baseAddress, Vector128< /// public static unsafe Vector128 GatherVector128(uint* baseAddress, Vector128 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector128(baseAddress, index, 1); - case 2: - return GatherVector128(baseAddress, index, 2); - case 4: - return GatherVector128(baseAddress, index, 4); - case 8: - return GatherVector128(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector128(baseAddress, index, 1), + 2 => GatherVector128(baseAddress, index, 2), + 4 => GatherVector128(baseAddress, index, 4), + 8 => GatherVector128(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128i _mm_i32gather_epi64 (__int64 const* base_addr, __m128i vindex, const int scale) @@ -890,19 +880,14 @@ public static unsafe Vector128 GatherVector128(uint* baseAddress, Vector12 /// public static unsafe Vector128 GatherVector128(long* baseAddress, Vector128 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector128(baseAddress, index, 1); - case 2: - return GatherVector128(baseAddress, index, 2); - case 4: - return GatherVector128(baseAddress, index, 4); - case 8: - return GatherVector128(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector128(baseAddress, index, 1), + 2 => GatherVector128(baseAddress, index, 2), + 4 => GatherVector128(baseAddress, index, 4), + 8 => GatherVector128(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128i _mm_i32gather_epi64 (__int64 const* base_addr, __m128i vindex, const int scale) @@ -911,19 +896,14 @@ public static unsafe Vector128 GatherVector128(long* baseAddress, Vector12 /// public static unsafe Vector128 GatherVector128(ulong* baseAddress, Vector128 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector128(baseAddress, index, 1); - case 2: - return GatherVector128(baseAddress, index, 2); - case 4: - return GatherVector128(baseAddress, index, 4); - case 8: - return GatherVector128(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector128(baseAddress, index, 1), + 2 => GatherVector128(baseAddress, index, 2), + 4 => GatherVector128(baseAddress, index, 4), + 8 => GatherVector128(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128 _mm_i32gather_ps (float const* base_addr, __m128i vindex, const int scale) @@ -932,19 +912,14 @@ public static unsafe Vector128 GatherVector128(ulong* baseAddress, Vector /// public static unsafe Vector128 GatherVector128(float* baseAddress, Vector128 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector128(baseAddress, index, 1); - case 2: - return GatherVector128(baseAddress, index, 2); - case 4: - return GatherVector128(baseAddress, index, 4); - case 8: - return GatherVector128(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector128(baseAddress, index, 1), + 2 => GatherVector128(baseAddress, index, 2), + 4 => GatherVector128(baseAddress, index, 4), + 8 => GatherVector128(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128d _mm_i32gather_pd (double const* base_addr, __m128i vindex, const int scale) @@ -953,19 +928,14 @@ public static unsafe Vector128 GatherVector128(float* baseAddress, Vector /// public static unsafe Vector128 GatherVector128(double* baseAddress, Vector128 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector128(baseAddress, index, 1); - case 2: - return GatherVector128(baseAddress, index, 2); - case 4: - return GatherVector128(baseAddress, index, 4); - case 8: - return GatherVector128(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector128(baseAddress, index, 1), + 2 => GatherVector128(baseAddress, index, 2), + 4 => GatherVector128(baseAddress, index, 4), + 8 => GatherVector128(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128i _mm_i64gather_epi32 (int const* base_addr, __m128i vindex, const int scale) @@ -974,19 +944,14 @@ public static unsafe Vector128 GatherVector128(double* baseAddress, Vect /// public static unsafe Vector128 GatherVector128(int* baseAddress, Vector128 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector128(baseAddress, index, 1); - case 2: - return GatherVector128(baseAddress, index, 2); - case 4: - return GatherVector128(baseAddress, index, 4); - case 8: - return GatherVector128(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector128(baseAddress, index, 1), + 2 => GatherVector128(baseAddress, index, 2), + 4 => GatherVector128(baseAddress, index, 4), + 8 => GatherVector128(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128i _mm_i64gather_epi32 (int const* base_addr, __m128i vindex, const int scale) @@ -995,19 +960,14 @@ public static unsafe Vector128 GatherVector128(int* baseAddress, Vector128< /// public static unsafe Vector128 GatherVector128(uint* baseAddress, Vector128 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector128(baseAddress, index, 1); - case 2: - return GatherVector128(baseAddress, index, 2); - case 4: - return GatherVector128(baseAddress, index, 4); - case 8: - return GatherVector128(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector128(baseAddress, index, 1), + 2 => GatherVector128(baseAddress, index, 2), + 4 => GatherVector128(baseAddress, index, 4), + 8 => GatherVector128(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128i _mm_i64gather_epi64 (__int64 const* base_addr, __m128i vindex, const int scale) @@ -1016,19 +976,14 @@ public static unsafe Vector128 GatherVector128(uint* baseAddress, Vector12 /// public static unsafe Vector128 GatherVector128(long* baseAddress, Vector128 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector128(baseAddress, index, 1); - case 2: - return GatherVector128(baseAddress, index, 2); - case 4: - return GatherVector128(baseAddress, index, 4); - case 8: - return GatherVector128(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector128(baseAddress, index, 1), + 2 => GatherVector128(baseAddress, index, 2), + 4 => GatherVector128(baseAddress, index, 4), + 8 => GatherVector128(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128i _mm_i64gather_epi64 (__int64 const* base_addr, __m128i vindex, const int scale) @@ -1037,19 +992,14 @@ public static unsafe Vector128 GatherVector128(long* baseAddress, Vector12 /// public static unsafe Vector128 GatherVector128(ulong* baseAddress, Vector128 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector128(baseAddress, index, 1); - case 2: - return GatherVector128(baseAddress, index, 2); - case 4: - return GatherVector128(baseAddress, index, 4); - case 8: - return GatherVector128(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector128(baseAddress, index, 1), + 2 => GatherVector128(baseAddress, index, 2), + 4 => GatherVector128(baseAddress, index, 4), + 8 => GatherVector128(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128 _mm_i64gather_ps (float const* base_addr, __m128i vindex, const int scale) @@ -1058,19 +1008,14 @@ public static unsafe Vector128 GatherVector128(ulong* baseAddress, Vector /// public static unsafe Vector128 GatherVector128(float* baseAddress, Vector128 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector128(baseAddress, index, 1); - case 2: - return GatherVector128(baseAddress, index, 2); - case 4: - return GatherVector128(baseAddress, index, 4); - case 8: - return GatherVector128(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector128(baseAddress, index, 1), + 2 => GatherVector128(baseAddress, index, 2), + 4 => GatherVector128(baseAddress, index, 4), + 8 => GatherVector128(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128d _mm_i64gather_pd (double const* base_addr, __m128i vindex, const int scale) @@ -1079,19 +1024,14 @@ public static unsafe Vector128 GatherVector128(float* baseAddress, Vector /// public static unsafe Vector128 GatherVector128(double* baseAddress, Vector128 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector128(baseAddress, index, 1); - case 2: - return GatherVector128(baseAddress, index, 2); - case 4: - return GatherVector128(baseAddress, index, 4); - case 8: - return GatherVector128(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector128(baseAddress, index, 1), + 2 => GatherVector128(baseAddress, index, 2), + 4 => GatherVector128(baseAddress, index, 4), + 8 => GatherVector128(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m256i _mm256_i32gather_epi32 (int const* base_addr, __m256i vindex, const int scale) @@ -1100,19 +1040,14 @@ public static unsafe Vector128 GatherVector128(double* baseAddress, Vect /// public static unsafe Vector256 GatherVector256(int* baseAddress, Vector256 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector256(baseAddress, index, 1); - case 2: - return GatherVector256(baseAddress, index, 2); - case 4: - return GatherVector256(baseAddress, index, 4); - case 8: - return GatherVector256(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector256(baseAddress, index, 1), + 2 => GatherVector256(baseAddress, index, 2), + 4 => GatherVector256(baseAddress, index, 4), + 8 => GatherVector256(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m256i _mm256_i32gather_epi32 (int const* base_addr, __m256i vindex, const int scale) @@ -1121,19 +1056,14 @@ public static unsafe Vector256 GatherVector256(int* baseAddress, Vector256< /// public static unsafe Vector256 GatherVector256(uint* baseAddress, Vector256 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector256(baseAddress, index, 1); - case 2: - return GatherVector256(baseAddress, index, 2); - case 4: - return GatherVector256(baseAddress, index, 4); - case 8: - return GatherVector256(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector256(baseAddress, index, 1), + 2 => GatherVector256(baseAddress, index, 2), + 4 => GatherVector256(baseAddress, index, 4), + 8 => GatherVector256(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m256i _mm256_i32gather_epi64 (__int64 const* base_addr, __m128i vindex, const int scale) @@ -1142,19 +1072,14 @@ public static unsafe Vector256 GatherVector256(uint* baseAddress, Vector25 /// public static unsafe Vector256 GatherVector256(long* baseAddress, Vector128 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector256(baseAddress, index, 1); - case 2: - return GatherVector256(baseAddress, index, 2); - case 4: - return GatherVector256(baseAddress, index, 4); - case 8: - return GatherVector256(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector256(baseAddress, index, 1), + 2 => GatherVector256(baseAddress, index, 2), + 4 => GatherVector256(baseAddress, index, 4), + 8 => GatherVector256(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m256i _mm256_i32gather_epi64 (__int64 const* base_addr, __m128i vindex, const int scale) @@ -1163,19 +1088,14 @@ public static unsafe Vector256 GatherVector256(long* baseAddress, Vector12 /// public static unsafe Vector256 GatherVector256(ulong* baseAddress, Vector128 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector256(baseAddress, index, 1); - case 2: - return GatherVector256(baseAddress, index, 2); - case 4: - return GatherVector256(baseAddress, index, 4); - case 8: - return GatherVector256(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector256(baseAddress, index, 1), + 2 => GatherVector256(baseAddress, index, 2), + 4 => GatherVector256(baseAddress, index, 4), + 8 => GatherVector256(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m256 _mm256_i32gather_ps (float const* base_addr, __m256i vindex, const int scale) @@ -1184,19 +1104,14 @@ public static unsafe Vector256 GatherVector256(ulong* baseAddress, Vector /// public static unsafe Vector256 GatherVector256(float* baseAddress, Vector256 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector256(baseAddress, index, 1); - case 2: - return GatherVector256(baseAddress, index, 2); - case 4: - return GatherVector256(baseAddress, index, 4); - case 8: - return GatherVector256(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector256(baseAddress, index, 1), + 2 => GatherVector256(baseAddress, index, 2), + 4 => GatherVector256(baseAddress, index, 4), + 8 => GatherVector256(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m256d _mm256_i32gather_pd (double const* base_addr, __m128i vindex, const int scale) @@ -1205,19 +1120,14 @@ public static unsafe Vector256 GatherVector256(float* baseAddress, Vector /// public static unsafe Vector256 GatherVector256(double* baseAddress, Vector128 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector256(baseAddress, index, 1); - case 2: - return GatherVector256(baseAddress, index, 2); - case 4: - return GatherVector256(baseAddress, index, 4); - case 8: - return GatherVector256(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector256(baseAddress, index, 1), + 2 => GatherVector256(baseAddress, index, 2), + 4 => GatherVector256(baseAddress, index, 4), + 8 => GatherVector256(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128i _mm256_i64gather_epi32 (int const* base_addr, __m256i vindex, const int scale) @@ -1226,19 +1136,14 @@ public static unsafe Vector256 GatherVector256(double* baseAddress, Vect /// public static unsafe Vector128 GatherVector128(int* baseAddress, Vector256 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector128(baseAddress, index, 1); - case 2: - return GatherVector128(baseAddress, index, 2); - case 4: - return GatherVector128(baseAddress, index, 4); - case 8: - return GatherVector128(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector128(baseAddress, index, 1), + 2 => GatherVector128(baseAddress, index, 2), + 4 => GatherVector128(baseAddress, index, 4), + 8 => GatherVector128(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128i _mm256_i64gather_epi32 (int const* base_addr, __m256i vindex, const int scale) @@ -1247,19 +1152,14 @@ public static unsafe Vector128 GatherVector128(int* baseAddress, Vector256< /// public static unsafe Vector128 GatherVector128(uint* baseAddress, Vector256 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector128(baseAddress, index, 1); - case 2: - return GatherVector128(baseAddress, index, 2); - case 4: - return GatherVector128(baseAddress, index, 4); - case 8: - return GatherVector128(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector128(baseAddress, index, 1), + 2 => GatherVector128(baseAddress, index, 2), + 4 => GatherVector128(baseAddress, index, 4), + 8 => GatherVector128(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m256i _mm256_i64gather_epi64 (__int64 const* base_addr, __m256i vindex, const int scale) @@ -1268,19 +1168,14 @@ public static unsafe Vector128 GatherVector128(uint* baseAddress, Vector25 /// public static unsafe Vector256 GatherVector256(long* baseAddress, Vector256 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector256(baseAddress, index, 1); - case 2: - return GatherVector256(baseAddress, index, 2); - case 4: - return GatherVector256(baseAddress, index, 4); - case 8: - return GatherVector256(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector256(baseAddress, index, 1), + 2 => GatherVector256(baseAddress, index, 2), + 4 => GatherVector256(baseAddress, index, 4), + 8 => GatherVector256(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m256i _mm256_i64gather_epi64 (__int64 const* base_addr, __m256i vindex, const int scale) @@ -1289,19 +1184,14 @@ public static unsafe Vector256 GatherVector256(long* baseAddress, Vector25 /// public static unsafe Vector256 GatherVector256(ulong* baseAddress, Vector256 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector256(baseAddress, index, 1); - case 2: - return GatherVector256(baseAddress, index, 2); - case 4: - return GatherVector256(baseAddress, index, 4); - case 8: - return GatherVector256(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector256(baseAddress, index, 1), + 2 => GatherVector256(baseAddress, index, 2), + 4 => GatherVector256(baseAddress, index, 4), + 8 => GatherVector256(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128 _mm256_i64gather_ps (float const* base_addr, __m256i vindex, const int scale) @@ -1310,19 +1200,14 @@ public static unsafe Vector256 GatherVector256(ulong* baseAddress, Vector /// public static unsafe Vector128 GatherVector128(float* baseAddress, Vector256 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector128(baseAddress, index, 1); - case 2: - return GatherVector128(baseAddress, index, 2); - case 4: - return GatherVector128(baseAddress, index, 4); - case 8: - return GatherVector128(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector128(baseAddress, index, 1), + 2 => GatherVector128(baseAddress, index, 2), + 4 => GatherVector128(baseAddress, index, 4), + 8 => GatherVector128(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m256d _mm256_i64gather_pd (double const* base_addr, __m256i vindex, const int scale) @@ -1331,19 +1216,14 @@ public static unsafe Vector128 GatherVector128(float* baseAddress, Vector /// public static unsafe Vector256 GatherVector256(double* baseAddress, Vector256 index, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherVector256(baseAddress, index, 1); - case 2: - return GatherVector256(baseAddress, index, 2); - case 4: - return GatherVector256(baseAddress, index, 4); - case 8: - return GatherVector256(baseAddress, index, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherVector256(baseAddress, index, 1), + 2 => GatherVector256(baseAddress, index, 2), + 4 => GatherVector256(baseAddress, index, 4), + 8 => GatherVector256(baseAddress, index, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// @@ -1353,19 +1233,14 @@ public static unsafe Vector256 GatherVector256(double* baseAddress, Vect /// public static unsafe Vector128 GatherMaskVector128(Vector128 source, int* baseAddress, Vector128 index, Vector128 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector128(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector128(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector128(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector128(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128i _mm_mask_i32gather_epi32 (__m128i src, int const* base_addr, __m128i vindex, __m128i mask, const int scale) @@ -1374,19 +1249,14 @@ public static unsafe Vector128 GatherMaskVector128(Vector128 source, i /// public static unsafe Vector128 GatherMaskVector128(Vector128 source, uint* baseAddress, Vector128 index, Vector128 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector128(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector128(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector128(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector128(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128i _mm_mask_i32gather_epi64 (__m128i src, __int64 const* base_addr, __m128i vindex, __m128i mask, const int scale) @@ -1395,19 +1265,14 @@ public static unsafe Vector128 GatherMaskVector128(Vector128 source, /// public static unsafe Vector128 GatherMaskVector128(Vector128 source, long* baseAddress, Vector128 index, Vector128 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector128(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector128(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector128(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector128(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128i _mm_mask_i32gather_epi64 (__m128i src, __int64 const* base_addr, __m128i vindex, __m128i mask, const int scale) @@ -1416,19 +1281,14 @@ public static unsafe Vector128 GatherMaskVector128(Vector128 source, /// public static unsafe Vector128 GatherMaskVector128(Vector128 source, ulong* baseAddress, Vector128 index, Vector128 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector128(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector128(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector128(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector128(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128 _mm_mask_i32gather_ps (__m128 src, float const* base_addr, __m128i vindex, __m128 mask, const int scale) @@ -1437,19 +1297,14 @@ public static unsafe Vector128 GatherMaskVector128(Vector128 sourc /// public static unsafe Vector128 GatherMaskVector128(Vector128 source, float* baseAddress, Vector128 index, Vector128 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector128(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector128(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector128(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector128(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128d _mm_mask_i32gather_pd (__m128d src, double const* base_addr, __m128i vindex, __m128d mask, const int scale) @@ -1458,19 +1313,14 @@ public static unsafe Vector128 GatherMaskVector128(Vector128 sourc /// public static unsafe Vector128 GatherMaskVector128(Vector128 source, double* baseAddress, Vector128 index, Vector128 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector128(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector128(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector128(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector128(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128i _mm_mask_i64gather_epi32 (__m128i src, int const* base_addr, __m128i vindex, __m128i mask, const int scale) @@ -1479,19 +1329,14 @@ public static unsafe Vector128 GatherMaskVector128(Vector128 sou /// public static unsafe Vector128 GatherMaskVector128(Vector128 source, int* baseAddress, Vector128 index, Vector128 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector128(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector128(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector128(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector128(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128i _mm_mask_i64gather_epi32 (__m128i src, int const* base_addr, __m128i vindex, __m128i mask, const int scale) @@ -1500,19 +1345,14 @@ public static unsafe Vector128 GatherMaskVector128(Vector128 source, i /// public static unsafe Vector128 GatherMaskVector128(Vector128 source, uint* baseAddress, Vector128 index, Vector128 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector128(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector128(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector128(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector128(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128i _mm_mask_i64gather_epi64 (__m128i src, __int64 const* base_addr, __m128i vindex, __m128i mask, const int scale) @@ -1521,19 +1361,14 @@ public static unsafe Vector128 GatherMaskVector128(Vector128 source, /// public static unsafe Vector128 GatherMaskVector128(Vector128 source, long* baseAddress, Vector128 index, Vector128 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector128(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector128(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector128(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector128(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128i _mm_mask_i64gather_epi64 (__m128i src, __int64 const* base_addr, __m128i vindex, __m128i mask, const int scale) @@ -1542,19 +1377,14 @@ public static unsafe Vector128 GatherMaskVector128(Vector128 source, /// public static unsafe Vector128 GatherMaskVector128(Vector128 source, ulong* baseAddress, Vector128 index, Vector128 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector128(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector128(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector128(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector128(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128 _mm_mask_i64gather_ps (__m128 src, float const* base_addr, __m128i vindex, __m128 mask, const int scale) @@ -1563,19 +1393,14 @@ public static unsafe Vector128 GatherMaskVector128(Vector128 sourc /// public static unsafe Vector128 GatherMaskVector128(Vector128 source, float* baseAddress, Vector128 index, Vector128 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector128(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector128(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector128(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector128(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128d _mm_mask_i64gather_pd (__m128d src, double const* base_addr, __m128i vindex, __m128d mask, const int scale) @@ -1584,19 +1409,14 @@ public static unsafe Vector128 GatherMaskVector128(Vector128 sourc /// public static unsafe Vector128 GatherMaskVector128(Vector128 source, double* baseAddress, Vector128 index, Vector128 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector128(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector128(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector128(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector128(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m256i _mm256_mask_i32gather_epi32 (__m256i src, int const* base_addr, __m256i vindex, __m256i mask, const int scale) @@ -1605,19 +1425,14 @@ public static unsafe Vector128 GatherMaskVector128(Vector128 sou /// public static unsafe Vector256 GatherMaskVector256(Vector256 source, int* baseAddress, Vector256 index, Vector256 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector256(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector256(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector256(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector256(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector256(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector256(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector256(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector256(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m256i _mm256_mask_i32gather_epi32 (__m256i src, int const* base_addr, __m256i vindex, __m256i mask, const int scale) @@ -1626,19 +1441,14 @@ public static unsafe Vector256 GatherMaskVector256(Vector256 source, i /// public static unsafe Vector256 GatherMaskVector256(Vector256 source, uint* baseAddress, Vector256 index, Vector256 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector256(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector256(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector256(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector256(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector256(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector256(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector256(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector256(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m256i _mm256_mask_i32gather_epi64 (__m256i src, __int64 const* base_addr, __m128i vindex, __m256i mask, const int scale) @@ -1647,19 +1457,14 @@ public static unsafe Vector256 GatherMaskVector256(Vector256 source, /// public static unsafe Vector256 GatherMaskVector256(Vector256 source, long* baseAddress, Vector128 index, Vector256 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector256(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector256(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector256(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector256(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector256(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector256(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector256(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector256(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m256i _mm256_mask_i32gather_epi64 (__m256i src, __int64 const* base_addr, __m128i vindex, __m256i mask, const int scale) @@ -1668,19 +1473,14 @@ public static unsafe Vector256 GatherMaskVector256(Vector256 source, /// public static unsafe Vector256 GatherMaskVector256(Vector256 source, ulong* baseAddress, Vector128 index, Vector256 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector256(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector256(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector256(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector256(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector256(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector256(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector256(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector256(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m256 _mm256_mask_i32gather_ps (__m256 src, float const* base_addr, __m256i vindex, __m256 mask, const int scale) @@ -1689,19 +1489,14 @@ public static unsafe Vector256 GatherMaskVector256(Vector256 sourc /// public static unsafe Vector256 GatherMaskVector256(Vector256 source, float* baseAddress, Vector256 index, Vector256 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector256(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector256(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector256(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector256(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector256(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector256(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector256(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector256(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m256d _mm256_mask_i32gather_pd (__m256d src, double const* base_addr, __m128i vindex, __m256d mask, const int scale) @@ -1710,19 +1505,14 @@ public static unsafe Vector256 GatherMaskVector256(Vector256 sourc /// public static unsafe Vector256 GatherMaskVector256(Vector256 source, double* baseAddress, Vector128 index, Vector256 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector256(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector256(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector256(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector256(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector256(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector256(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector256(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector256(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128i _mm256_mask_i64gather_epi32 (__m128i src, int const* base_addr, __m256i vindex, __m128i mask, const int scale) @@ -1731,19 +1521,14 @@ public static unsafe Vector256 GatherMaskVector256(Vector256 sou /// public static unsafe Vector128 GatherMaskVector128(Vector128 source, int* baseAddress, Vector256 index, Vector128 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector128(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector128(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector128(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector128(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128i _mm256_mask_i64gather_epi32 (__m128i src, int const* base_addr, __m256i vindex, __m128i mask, const int scale) @@ -1752,19 +1537,14 @@ public static unsafe Vector128 GatherMaskVector128(Vector128 source, i /// public static unsafe Vector128 GatherMaskVector128(Vector128 source, uint* baseAddress, Vector256 index, Vector128 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector128(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector128(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector128(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector128(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m256i _mm256_mask_i64gather_epi64 (__m256i src, __int64 const* base_addr, __m256i vindex, __m256i mask, const int scale) @@ -1773,19 +1553,14 @@ public static unsafe Vector128 GatherMaskVector128(Vector128 source, /// public static unsafe Vector256 GatherMaskVector256(Vector256 source, long* baseAddress, Vector256 index, Vector256 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector256(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector256(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector256(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector256(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector256(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector256(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector256(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector256(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m256i _mm256_mask_i64gather_epi64 (__m256i src, __int64 const* base_addr, __m256i vindex, __m256i mask, const int scale) @@ -1794,19 +1569,14 @@ public static unsafe Vector256 GatherMaskVector256(Vector256 source, /// public static unsafe Vector256 GatherMaskVector256(Vector256 source, ulong* baseAddress, Vector256 index, Vector256 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector256(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector256(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector256(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector256(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector256(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector256(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector256(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector256(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m128 _mm256_mask_i64gather_ps (__m128 src, float const* base_addr, __m256i vindex, __m128 mask, const int scale) @@ -1815,19 +1585,14 @@ public static unsafe Vector256 GatherMaskVector256(Vector256 sourc /// public static unsafe Vector128 GatherMaskVector128(Vector128 source, float* baseAddress, Vector256 index, Vector128 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector128(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector128(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector128(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector128(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// /// __m256d _mm256_mask_i64gather_pd (__m256d src, double const* base_addr, __m256i vindex, __m256d mask, const int scale) @@ -1836,19 +1601,14 @@ public static unsafe Vector128 GatherMaskVector128(Vector128 sourc /// public static unsafe Vector256 GatherMaskVector256(Vector256 source, double* baseAddress, Vector256 index, Vector256 mask, byte scale) { - switch (scale) + return scale switch { - case 1: - return GatherMaskVector256(source, baseAddress, index, mask, 1); - case 2: - return GatherMaskVector256(source, baseAddress, index, mask, 2); - case 4: - return GatherMaskVector256(source, baseAddress, index, mask, 4); - case 8: - return GatherMaskVector256(source, baseAddress, index, mask, 8); - default: - throw new ArgumentOutOfRangeException(nameof(scale)); - } + 1 => GatherMaskVector256(source, baseAddress, index, mask, 1), + 2 => GatherMaskVector256(source, baseAddress, index, mask, 2), + 4 => GatherMaskVector256(source, baseAddress, index, mask, 4), + 8 => GatherMaskVector256(source, baseAddress, index, mask, 8), + _ => throw new ArgumentOutOfRangeException(nameof(scale)), + }; } /// diff --git a/src/System.Private.CoreLib/shared/System/Security/SecurityElement.cs b/src/System.Private.CoreLib/shared/System/Security/SecurityElement.cs index 8965aefe6787..f9e4f686d81e 100644 --- a/src/System.Private.CoreLib/shared/System/Security/SecurityElement.cs +++ b/src/System.Private.CoreLib/shared/System/Security/SecurityElement.cs @@ -202,8 +202,7 @@ internal void ConvertSecurityElementFactories() for (int i = 0; i < _children.Count; ++i) { - ISecurityElementFactory? iseFactory = _children[i] as ISecurityElementFactory; - if (iseFactory != null && !(_children[i] is SecurityElement)) + if (_children[i] is ISecurityElementFactory iseFactory && !(_children[i] is SecurityElement)) _children[i] = iseFactory.CreateSecurityElement(); } } diff --git a/src/System.Private.CoreLib/shared/System/StringComparer.cs b/src/System.Private.CoreLib/shared/System/StringComparer.cs index f55a098306c7..f9bd66f286e1 100644 --- a/src/System.Private.CoreLib/shared/System/StringComparer.cs +++ b/src/System.Private.CoreLib/shared/System/StringComparer.cs @@ -69,23 +69,16 @@ public static StringComparer OrdinalIgnoreCase // Convert a StringComparison to a StringComparer public static StringComparer FromComparison(StringComparison comparisonType) { - switch (comparisonType) + return comparisonType switch { - case StringComparison.CurrentCulture: - return CurrentCulture; - case StringComparison.CurrentCultureIgnoreCase: - return CurrentCultureIgnoreCase; - case StringComparison.InvariantCulture: - return InvariantCulture; - case StringComparison.InvariantCultureIgnoreCase: - return InvariantCultureIgnoreCase; - case StringComparison.Ordinal: - return Ordinal; - case StringComparison.OrdinalIgnoreCase: - return OrdinalIgnoreCase; - default: - throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); - } + StringComparison.CurrentCulture => CurrentCulture, + StringComparison.CurrentCultureIgnoreCase => CurrentCultureIgnoreCase, + StringComparison.InvariantCulture => InvariantCulture, + StringComparison.InvariantCultureIgnoreCase => InvariantCultureIgnoreCase, + StringComparison.Ordinal => Ordinal, + StringComparison.OrdinalIgnoreCase => OrdinalIgnoreCase, + _ => throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)), + }; } public static StringComparer Create(CultureInfo culture, bool ignoreCase) diff --git a/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs b/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs index 2e414cf8d0f4..aaec29694785 100644 --- a/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs @@ -873,8 +873,7 @@ public override int MaxCharCount public override bool Equals(object? value) { - DecoderUTF7Fallback? that = value as DecoderUTF7Fallback; - if (that != null) + if (value is DecoderUTF7Fallback) { return true; } diff --git a/src/System.Private.CoreLib/shared/System/Threading/CancellationTokenSource.cs b/src/System.Private.CoreLib/shared/System/Threading/CancellationTokenSource.cs index 704e2c1d7478..dec0eab801a2 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/CancellationTokenSource.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/CancellationTokenSource.cs @@ -773,19 +773,16 @@ public static CancellationTokenSource CreateLinkedTokenSource(params Cancellatio throw new ArgumentNullException(nameof(tokens)); } - switch (tokens.Length) + return tokens.Length switch { - case 0: - throw new ArgumentException(SR.CancellationToken_CreateLinkedToken_TokensIsEmpty); - case 1: - return CreateLinkedTokenSource(tokens[0]); - case 2: - return CreateLinkedTokenSource(tokens[0], tokens[1]); - default: - // a defensive copy is not required as the array has value-items that have only a single reference field, - // hence each item cannot be null itself, and reads of the payloads cannot be torn. - return new LinkedNCancellationTokenSource(tokens); - } + 0 => throw new ArgumentException(SR.CancellationToken_CreateLinkedToken_TokensIsEmpty), + 1 => CreateLinkedTokenSource(tokens[0]), + 2 => CreateLinkedTokenSource(tokens[0], tokens[1]), + + // a defensive copy is not required as the array has value-items that have only a single reference field, + // hence each item cannot be null itself, and reads of the payloads cannot be torn. + _ => new LinkedNCancellationTokenSource(tokens), + }; } /// diff --git a/src/System.Private.CoreLib/shared/System/Threading/Tasks/Task.cs b/src/System.Private.CoreLib/shared/System/Threading/Tasks/Task.cs index 53d35fbdf1cb..c1a5ac3ed9fb 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/Tasks/Task.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/Tasks/Task.cs @@ -6659,10 +6659,9 @@ private bool TrySetFromTask(Task task, bool lookForOce) case TaskStatus.Faulted: var edis = task.GetExceptionDispatchInfos(); ExceptionDispatchInfo oceEdi; - OperationCanceledException? oce; if (lookForOce && edis.Count > 0 && (oceEdi = edis[0]) != null && - (oce = oceEdi.SourceException as OperationCanceledException) != null) + oceEdi.SourceException is OperationCanceledException oce) { result = TrySetCanceled(oce.CancellationToken, oceEdi); } @@ -6673,15 +6672,13 @@ private bool TrySetFromTask(Task task, bool lookForOce) break; case TaskStatus.RanToCompletion: - var taskTResult = task as Task; - if (AsyncCausalityTracer.LoggingOn) AsyncCausalityTracer.TraceOperationCompletion(this, AsyncCausalityStatus.Completed); if (Task.s_asyncDebuggingEnabled) RemoveFromActiveTasks(this); - result = TrySetResult(taskTResult != null ? taskTResult.Result : default); + result = TrySetResult(task is Task taskTResult ? taskTResult.Result : default); break; } return result; diff --git a/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskToApm.cs b/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskToApm.cs index aaa072fe6055..0343fbaefaab 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskToApm.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskToApm.cs @@ -67,8 +67,7 @@ public static void End(IAsyncResult asyncResult) Task? task; // If the IAsyncResult is our task-wrapping IAsyncResult, extract the Task. - var twar = asyncResult as TaskWrapperAsyncResult; - if (twar != null) + if (asyncResult is TaskWrapperAsyncResult twar) { task = twar.Task; Debug.Assert(task != null, "TaskWrapperAsyncResult should never wrap a null Task."); @@ -95,8 +94,7 @@ public static TResult End(IAsyncResult asyncResult) Task? task; // If the IAsyncResult is our task-wrapping IAsyncResult, extract the Task. - var twar = asyncResult as TaskWrapperAsyncResult; - if (twar != null) + if (asyncResult is TaskWrapperAsyncResult twar) { task = twar.Task as Task; Debug.Assert(twar.Task != null, "TaskWrapperAsyncResult should never wrap a null Task."); diff --git a/src/System.Private.CoreLib/shared/System/Tuple.cs b/src/System.Private.CoreLib/shared/System/Tuple.cs index 9c77f0245dba..1d3f045845f9 100644 --- a/src/System.Private.CoreLib/shared/System/Tuple.cs +++ b/src/System.Private.CoreLib/shared/System/Tuple.cs @@ -296,15 +296,12 @@ string ITupleInternal.ToString(StringBuilder sb) { get { - switch (index) + return index switch { - case 0: - return Item1; - case 1: - return Item2; - default: - throw new IndexOutOfRangeException(); - } + 0 => Item1, + 1 => Item2, + _ => throw new IndexOutOfRangeException(), + }; } } } @@ -416,17 +413,13 @@ string ITupleInternal.ToString(StringBuilder sb) { get { - switch (index) + return index switch { - case 0: - return Item1; - case 1: - return Item2; - case 2: - return Item3; - default: - throw new IndexOutOfRangeException(); - } + 0 => Item1, + 1 => Item2, + 2 => Item3, + _ => throw new IndexOutOfRangeException(), + }; } } } @@ -547,19 +540,14 @@ string ITupleInternal.ToString(StringBuilder sb) { get { - switch (index) + return index switch { - case 0: - return Item1; - case 1: - return Item2; - case 2: - return Item3; - case 3: - return Item4; - default: - throw new IndexOutOfRangeException(); - } + 0 => Item1, + 1 => Item2, + 2 => Item3, + 3 => Item4, + _ => throw new IndexOutOfRangeException(), + }; } } } @@ -689,21 +677,15 @@ string ITupleInternal.ToString(StringBuilder sb) { get { - switch (index) + return index switch { - case 0: - return Item1; - case 1: - return Item2; - case 2: - return Item3; - case 3: - return Item4; - case 4: - return Item5; - default: - throw new IndexOutOfRangeException(); - } + 0 => Item1, + 1 => Item2, + 2 => Item3, + 3 => Item4, + 4 => Item5, + _ => throw new IndexOutOfRangeException(), + }; } } } @@ -842,23 +824,16 @@ string ITupleInternal.ToString(StringBuilder sb) { get { - switch (index) + return index switch { - case 0: - return Item1; - case 1: - return Item2; - case 2: - return Item3; - case 3: - return Item4; - case 4: - return Item5; - case 5: - return Item6; - default: - throw new IndexOutOfRangeException(); - } + 0 => Item1, + 1 => Item2, + 2 => Item3, + 3 => Item4, + 4 => Item5, + 5 => Item6, + _ => throw new IndexOutOfRangeException(), + }; } } } @@ -1006,25 +981,17 @@ string ITupleInternal.ToString(StringBuilder sb) { get { - switch (index) + return index switch { - case 0: - return Item1; - case 1: - return Item2; - case 2: - return Item3; - case 3: - return Item4; - case 4: - return Item5; - case 5: - return Item6; - case 6: - return Item7; - default: - throw new IndexOutOfRangeException(); - } + 0 => Item1, + 1 => Item2, + 2 => Item3, + 3 => Item4, + 4 => Item5, + 5 => Item6, + 6 => Item7, + _ => throw new IndexOutOfRangeException(), + }; } } } @@ -1214,25 +1181,18 @@ int ITuple.Length { get { - switch (index) + return index switch { - case 0: - return Item1; - case 1: - return Item2; - case 2: - return Item3; - case 3: - return Item4; - case 4: - return Item5; - case 5: - return Item6; - case 6: - return Item7; - } - - return ((ITupleInternal)Rest)[index - 7]; + 0 => Item1, + 1 => Item2, + 2 => Item3, + 3 => Item4, + 4 => Item5, + 5 => Item6, + 6 => Item7, + + _ => ((ITupleInternal)Rest)[index - 7], + }; } } } diff --git a/src/System.Private.CoreLib/shared/System/ValueTuple.cs b/src/System.Private.CoreLib/shared/System/ValueTuple.cs index 6fd28db31e16..216ef5c697b0 100644 --- a/src/System.Private.CoreLib/shared/System/ValueTuple.cs +++ b/src/System.Private.CoreLib/shared/System/ValueTuple.cs @@ -656,15 +656,12 @@ string IValueTupleInternal.ToStringEnd() { get { - switch (index) + return index switch { - case 0: - return Item1; - case 1: - return Item2; - default: - throw new IndexOutOfRangeException(); - } + 0 => Item1, + 1 => Item2, + _ => throw new IndexOutOfRangeException(), + }; } } } @@ -862,17 +859,13 @@ string IValueTupleInternal.ToStringEnd() { get { - switch (index) + return index switch { - case 0: - return Item1; - case 1: - return Item2; - case 2: - return Item3; - default: - throw new IndexOutOfRangeException(); - } + 0 => Item1, + 1 => Item2, + 2 => Item3, + _ => throw new IndexOutOfRangeException(), + }; } } } @@ -1087,19 +1080,14 @@ string IValueTupleInternal.ToStringEnd() { get { - switch (index) + return index switch { - case 0: - return Item1; - case 1: - return Item2; - case 2: - return Item3; - case 3: - return Item4; - default: - throw new IndexOutOfRangeException(); - } + 0 => Item1, + 1 => Item2, + 2 => Item3, + 3 => Item4, + _ => throw new IndexOutOfRangeException(), + }; } } } @@ -1331,21 +1319,15 @@ string IValueTupleInternal.ToStringEnd() { get { - switch (index) + return index switch { - case 0: - return Item1; - case 1: - return Item2; - case 2: - return Item3; - case 3: - return Item4; - case 4: - return Item5; - default: - throw new IndexOutOfRangeException(); - } + 0 => Item1, + 1 => Item2, + 2 => Item3, + 3 => Item4, + 4 => Item5, + _ => throw new IndexOutOfRangeException(), + }; } } } @@ -1594,23 +1576,16 @@ string IValueTupleInternal.ToStringEnd() { get { - switch (index) + return index switch { - case 0: - return Item1; - case 1: - return Item2; - case 2: - return Item3; - case 3: - return Item4; - case 4: - return Item5; - case 5: - return Item6; - default: - throw new IndexOutOfRangeException(); - } + 0 => Item1, + 1 => Item2, + 2 => Item3, + 3 => Item4, + 4 => Item5, + 5 => Item6, + _ => throw new IndexOutOfRangeException(), + }; } } } @@ -1876,25 +1851,17 @@ string IValueTupleInternal.ToStringEnd() { get { - switch (index) + return index switch { - case 0: - return Item1; - case 1: - return Item2; - case 2: - return Item3; - case 3: - return Item4; - case 4: - return Item5; - case 5: - return Item6; - case 6: - return Item7; - default: - throw new IndexOutOfRangeException(); - } + 0 => Item1, + 1 => Item2, + 2 => Item3, + 3 => Item4, + 4 => Item5, + 5 => Item6, + 6 => Item7, + _ => throw new IndexOutOfRangeException(), + }; } } } @@ -2122,8 +2089,7 @@ int IStructuralComparable.CompareTo(object? other, IComparer comparer) public override int GetHashCode() { // We want to have a limited hash in this case. We'll use the last 8 elements of the tuple - IValueTupleInternal? rest = Rest as IValueTupleInternal; - if (rest == null) + if (!(Rest is IValueTupleInternal rest)) { return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0, Item2?.GetHashCode() ?? 0, @@ -2198,8 +2164,7 @@ int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) private int GetHashCodeCore(IEqualityComparer comparer) { // We want to have a limited hash in this case. We'll use the last 8 elements of the tuple - IValueTupleInternal? rest = Rest as IValueTupleInternal; - if (rest == null) + if (!(Rest is IValueTupleInternal rest)) { return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1!), comparer.GetHashCode(Item2!), comparer.GetHashCode(Item3!), comparer.GetHashCode(Item4!), comparer.GetHashCode(Item5!), comparer.GetHashCode(Item6!), @@ -2256,41 +2221,28 @@ int IValueTupleInternal.GetHashCode(IEqualityComparer comparer) /// public override string ToString() { - IValueTupleInternal? rest = Rest as IValueTupleInternal; - if (rest == null) - { - return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + Rest.ToString() + ")"; - } - else + if (Rest is IValueTupleInternal rest) { return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + rest.ToStringEnd(); } + + return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + Rest.ToString() + ")"; } string IValueTupleInternal.ToStringEnd() { - IValueTupleInternal? rest = Rest as IValueTupleInternal; - if (rest == null) - { - return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + Rest.ToString() + ")"; - } - else + if (Rest is IValueTupleInternal rest) { return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + rest.ToStringEnd(); } + + return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + Rest.ToString() + ")"; } /// /// The number of positions in this data structure. /// - int ITuple.Length - { - get - { - IValueTupleInternal? rest = Rest as IValueTupleInternal; - return rest == null ? 8 : 7 + rest.Length; - } - } + int ITuple.Length => Rest is IValueTupleInternal rest ? 7 + rest.Length : 8; /// /// Get the element at position . @@ -2317,16 +2269,18 @@ int ITuple.Length return Item7; } - IValueTupleInternal? rest = Rest as IValueTupleInternal; - if (rest == null) + if (Rest is IValueTupleInternal rest) { - if (index == 7) - { - return Rest; - } - throw new IndexOutOfRangeException(); + return rest[index - 7]; + } + + + if (index == 7) + { + return Rest; } - return rest[index - 7]; + + throw new IndexOutOfRangeException(); } } } diff --git a/src/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs index 75c40f05f601..1a71dcbcecf1 100644 --- a/src/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs @@ -452,17 +452,12 @@ public static Attribute[] GetCustomAttributes(MemberInfo element, Type type, boo if (!type.IsSubclassOf(typeof(Attribute)) && type != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); - switch (element.MemberType) + return element.MemberType switch { - case MemberTypes.Property: - return InternalGetCustomAttributes((PropertyInfo)element, type, inherit); - - case MemberTypes.Event: - return InternalGetCustomAttributes((EventInfo)element, type, inherit); - - default: - return (element.GetCustomAttributes(type, inherit) as Attribute[])!; - } + MemberTypes.Property => InternalGetCustomAttributes((PropertyInfo)element, type, inherit), + MemberTypes.Event => InternalGetCustomAttributes((EventInfo)element, type, inherit), + _ => (element.GetCustomAttributes(type, inherit) as Attribute[])!, + }; } public static Attribute[] GetCustomAttributes(MemberInfo element) @@ -475,17 +470,12 @@ public static Attribute[] GetCustomAttributes(MemberInfo element, bool inherit) if (element == null) throw new ArgumentNullException(nameof(element)); - switch (element.MemberType) + return element.MemberType switch { - case MemberTypes.Property: - return InternalGetCustomAttributes((PropertyInfo)element, typeof(Attribute), inherit); - - case MemberTypes.Event: - return InternalGetCustomAttributes((EventInfo)element, typeof(Attribute), inherit); - - default: - return (element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[])!; - } + MemberTypes.Property => InternalGetCustomAttributes((PropertyInfo)element, typeof(Attribute), inherit), + MemberTypes.Event => InternalGetCustomAttributes((EventInfo)element, typeof(Attribute), inherit), + _ => (element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[])!, + }; } public static bool IsDefined(MemberInfo element, Type attributeType) @@ -505,17 +495,12 @@ public static bool IsDefined(MemberInfo element, Type attributeType, bool inheri if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); - switch (element.MemberType) + return element.MemberType switch { - case MemberTypes.Property: - return InternalIsDefined((PropertyInfo)element, attributeType, inherit); - - case MemberTypes.Event: - return InternalIsDefined((EventInfo)element, attributeType, inherit); - - default: - return element.IsDefined(attributeType, inherit); - } + MemberTypes.Property => InternalIsDefined((PropertyInfo)element, attributeType, inherit), + MemberTypes.Event => InternalIsDefined((EventInfo)element, attributeType, inherit), + _ => element.IsDefined(attributeType, inherit), + }; } public static Attribute? GetCustomAttribute(MemberInfo element, Type attributeType) diff --git a/src/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs b/src/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs index 66ceb1586bcf..24b11bb7ae7b 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs @@ -505,62 +505,27 @@ public readonly partial struct CustomAttributeTypedArgument #region Private Static Methods private static Type CustomAttributeEncodingToType(CustomAttributeEncoding encodedType) { - switch (encodedType) - { - case (CustomAttributeEncoding.Enum): - return typeof(Enum); - - case (CustomAttributeEncoding.Int32): - return typeof(int); - - case (CustomAttributeEncoding.String): - return typeof(string); - - case (CustomAttributeEncoding.Type): - return typeof(Type); - - case (CustomAttributeEncoding.Array): - return typeof(Array); - - case (CustomAttributeEncoding.Char): - return typeof(char); - - case (CustomAttributeEncoding.Boolean): - return typeof(bool); - - case (CustomAttributeEncoding.SByte): - return typeof(sbyte); - - case (CustomAttributeEncoding.Byte): - return typeof(byte); - - case (CustomAttributeEncoding.Int16): - return typeof(short); - - case (CustomAttributeEncoding.UInt16): - return typeof(ushort); - - case (CustomAttributeEncoding.UInt32): - return typeof(uint); - - case (CustomAttributeEncoding.Int64): - return typeof(long); - - case (CustomAttributeEncoding.UInt64): - return typeof(ulong); - - case (CustomAttributeEncoding.Float): - return typeof(float); - - case (CustomAttributeEncoding.Double): - return typeof(double); - - case (CustomAttributeEncoding.Object): - return typeof(object); - - default: - throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)encodedType), nameof(encodedType)); - } + return encodedType switch + { + CustomAttributeEncoding.Enum => typeof(Enum), + CustomAttributeEncoding.Int32 => typeof(int), + CustomAttributeEncoding.String => typeof(string), + CustomAttributeEncoding.Type => typeof(Type), + CustomAttributeEncoding.Array => typeof(Array), + CustomAttributeEncoding.Char => typeof(char), + CustomAttributeEncoding.Boolean => typeof(bool), + CustomAttributeEncoding.SByte => typeof(sbyte), + CustomAttributeEncoding.Byte => typeof(byte), + CustomAttributeEncoding.Int16 => typeof(short), + CustomAttributeEncoding.UInt16 => typeof(ushort), + CustomAttributeEncoding.UInt32 => typeof(uint), + CustomAttributeEncoding.Int64 => typeof(long), + CustomAttributeEncoding.UInt64 => typeof(ulong), + CustomAttributeEncoding.Float => typeof(float), + CustomAttributeEncoding.Double => typeof(double), + CustomAttributeEncoding.Object => typeof(object), + _ => throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)encodedType), nameof(encodedType)), + }; } private static object EncodedValueToRawValue(long val, CustomAttributeEncoding encodedType) diff --git a/src/System.Private.CoreLib/src/System/Reflection/MdConstant.cs b/src/System.Private.CoreLib/src/System/Reflection/MdConstant.cs index 0fa1b385267f..144aa32043f5 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/MdConstant.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/MdConstant.cs @@ -111,64 +111,25 @@ internal static class MdConstant } else { - switch (corElementType) + return corElementType switch { - #region Switch - - case CorElementType.ELEMENT_TYPE_VOID: - return DBNull.Value; - - case CorElementType.ELEMENT_TYPE_CHAR: - return *(char*)&buffer; - - case CorElementType.ELEMENT_TYPE_I1: - return *(sbyte*)&buffer; - - case CorElementType.ELEMENT_TYPE_U1: - return *(byte*)&buffer; - - case CorElementType.ELEMENT_TYPE_I2: - return *(short*)&buffer; - - case CorElementType.ELEMENT_TYPE_U2: - return *(ushort*)&buffer; - - case CorElementType.ELEMENT_TYPE_I4: - return *(int*)&buffer; - - case CorElementType.ELEMENT_TYPE_U4: - return *(uint*)&buffer; - - case CorElementType.ELEMENT_TYPE_I8: - return buffer; - - case CorElementType.ELEMENT_TYPE_U8: - return (ulong)buffer; - - case CorElementType.ELEMENT_TYPE_BOOLEAN: - // The boolean value returned from the metadata engine is stored as a - // BOOL, which actually maps to an int. We need to read it out as an int - // to avoid problems on big-endian machines. - return (*(int*)&buffer != 0); - - case CorElementType.ELEMENT_TYPE_R4: - return *(float*)&buffer; - - case CorElementType.ELEMENT_TYPE_R8: - return *(double*)&buffer; - - case CorElementType.ELEMENT_TYPE_STRING: - // A string constant can be empty but never null. - // A nullref constant can only be type CorElementType.ELEMENT_TYPE_CLASS. - return stringVal == null ? string.Empty : stringVal; - - case CorElementType.ELEMENT_TYPE_CLASS: - return null; - - default: - throw new FormatException(SR.Arg_BadLiteralFormat); - #endregion - } + CorElementType.ELEMENT_TYPE_VOID => DBNull.Value, + CorElementType.ELEMENT_TYPE_CHAR => *(char*)&buffer, + CorElementType.ELEMENT_TYPE_I1 => *(sbyte*)&buffer, + CorElementType.ELEMENT_TYPE_U1 => *(byte*)&buffer, + CorElementType.ELEMENT_TYPE_I2 => *(short*)&buffer, + CorElementType.ELEMENT_TYPE_U2 => *(ushort*)&buffer, + CorElementType.ELEMENT_TYPE_I4 => *(int*)&buffer, + CorElementType.ELEMENT_TYPE_U4 => *(uint*)&buffer, + CorElementType.ELEMENT_TYPE_I8 => buffer, + CorElementType.ELEMENT_TYPE_U8 => (ulong)buffer, + CorElementType.ELEMENT_TYPE_BOOLEAN => (*(int*)&buffer != 0), + CorElementType.ELEMENT_TYPE_R4 => *(float*)&buffer, + CorElementType.ELEMENT_TYPE_R8 => *(double*)&buffer, + CorElementType.ELEMENT_TYPE_STRING => stringVal == null ? string.Empty : stringVal, + CorElementType.ELEMENT_TYPE_CLASS => null, + _ => throw new FormatException(SR.Arg_BadLiteralFormat), + }; } } } diff --git a/src/System.Private.CoreLib/src/System/Reflection/MdFieldInfo.cs b/src/System.Private.CoreLib/src/System/Reflection/MdFieldInfo.cs index f4cee246cc16..8200665eb447 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/MdFieldInfo.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/MdFieldInfo.cs @@ -31,12 +31,9 @@ internal MdFieldInfo( #region Internal Members internal override bool CacheEquals(object? o) { - MdFieldInfo? m = o as MdFieldInfo; - - if (m is null) - return false; - - return m.m_tkField == m_tkField && + return + o is MdFieldInfo m && + m.m_tkField == m_tkField && m_declaringType.GetTypeHandleInternal().GetModuleHandle().Equals( m.m_declaringType.GetTypeHandleInternal().GetModuleHandle()); } diff --git a/src/System.Private.CoreLib/src/System/Reflection/RtFieldInfo.cs b/src/System.Private.CoreLib/src/System/Reflection/RtFieldInfo.cs index 2f45c782076d..cb844cd38474 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/RtFieldInfo.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/RtFieldInfo.cs @@ -110,12 +110,7 @@ internal void CheckConsistency(object? target) internal override bool CacheEquals(object? o) { - RtFieldInfo? m = o as RtFieldInfo; - - if (m is null) - return false; - - return m.m_fieldHandle == m_fieldHandle; + return o is RtFieldInfo m && m.m_fieldHandle == m_fieldHandle; } #endregion diff --git a/src/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.cs b/src/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.cs index 004933af064c..9a8214207517 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.cs @@ -97,12 +97,7 @@ RuntimeMethodHandleInternal IRuntimeMethodInfo.Value internal override bool CacheEquals(object? o) { - RuntimeConstructorInfo? m = o as RuntimeConstructorInfo; - - if (m is null) - return false; - - return m.m_handle == m_handle; + return o is RuntimeConstructorInfo m && m.m_handle == m_handle; } private Signature Signature diff --git a/src/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs b/src/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs index 20c50fb1f9c3..ad8588310806 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs @@ -56,12 +56,9 @@ internal RuntimeEventInfo(int tkEvent, RuntimeType declaredType, RuntimeTypeCach #region Internal Members internal override bool CacheEquals(object? o) { - RuntimeEventInfo? m = o as RuntimeEventInfo; - - if (m is null) - return false; - - return m.m_token == m_token && + return + o is RuntimeEventInfo m && + m.m_token == m_token && RuntimeTypeHandle.GetModule(m_declaringType).Equals( RuntimeTypeHandle.GetModule(m.m_declaringType)); } diff --git a/src/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs b/src/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs index 465a6db92a11..58707a18589b 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs @@ -127,12 +127,7 @@ private ParameterInfo FetchReturnParameter() #region Internal Members internal override bool CacheEquals(object? o) { - RuntimeMethodInfo? m = o as RuntimeMethodInfo; - - if (m is null) - return false; - - return m.m_handle == m_handle; + return o is RuntimeMethodInfo m && m.m_handle == m_handle; } internal Signature Signature diff --git a/src/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs b/src/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs index 96e2fb370746..0febe692247f 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs @@ -55,12 +55,9 @@ internal RuntimePropertyInfo( #region Internal Members internal override bool CacheEquals(object? o) { - RuntimePropertyInfo? m = o as RuntimePropertyInfo; - - if (m is null) - return false; - - return m.m_token == m_token && + return + o is RuntimePropertyInfo m && + m.m_token == m_token && RuntimeTypeHandle.GetModule(m_declaringType).Equals( RuntimeTypeHandle.GetModule(m.m_declaringType)); } diff --git a/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs b/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs index 5e8b378ebd04..7f09a1ff3ef7 100644 --- a/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs @@ -3131,8 +3131,7 @@ public override bool IsSubclassOf(Type type) // Reflexive, symmetric, transitive. public override bool IsEquivalentTo(Type? other) { - var otherRtType = other as RuntimeType; - if (otherRtType is null) + if (!(other is RuntimeType otherRtType)) { return false; } @@ -4098,8 +4097,7 @@ private object CreateInstanceDefaultCtorSlow(bool publicOnly, bool wrapException internal object CreateInstanceDefaultCtor(bool publicOnly, bool skipCheckThis, bool fillCache, bool wrapExceptions) { // Call the cached - ActivatorCache? cacheEntry = GenericCache as ActivatorCache; - if (cacheEntry != null) + if (GenericCache is ActivatorCache cacheEntry) { cacheEntry.EnsureInitialized(); diff --git a/src/System.Private.CoreLib/src/System/StubHelpers.cs b/src/System.Private.CoreLib/src/System/StubHelpers.cs index f7ce565e9bfb..8357d7e4ba5a 100644 --- a/src/System.Private.CoreLib/src/System/StubHelpers.cs +++ b/src/System.Private.CoreLib/src/System/StubHelpers.cs @@ -1130,15 +1130,12 @@ internal IntPtr ConvertToNative(object pManagedHome, int dwFlags) } else { - string? strValue; - StringBuilder? sbValue; - - if ((strValue = pManagedHome as string) != null) + if (pManagedHome is string strValue) { // string (LPStr or LPWStr) pNativeHome = ConvertStringToNative(strValue, dwFlags); } - else if ((sbValue = pManagedHome as StringBuilder) != null) + else if (pManagedHome is StringBuilder sbValue) { // StringBuilder (LPStr or LPWStr) pNativeHome = ConvertStringBuilderToNative(sbValue, dwFlags); diff --git a/src/System.Private.CoreLib/src/System/Variant.cs b/src/System.Private.CoreLib/src/System/Variant.cs index 334bdc80e429..87840377670e 100644 --- a/src/System.Private.CoreLib/src/System/Variant.cs +++ b/src/System.Private.CoreLib/src/System/Variant.cs @@ -383,100 +383,43 @@ internal int CVType // managed variants as an intermediate type. internal static void MarshalHelperConvertObjectToVariant(object o, ref Variant v) { - IConvertible? ic = o as IConvertible; - if (o == null) { v = Empty; } - else if (ic == null) + else if (o is IConvertible ic) + { + IFormatProvider provider = CultureInfo.InvariantCulture; + v = ic.GetTypeCode() switch + { + TypeCode.Empty => Empty, + TypeCode.Object => new Variant((object)o), + TypeCode.DBNull => DBNull, + TypeCode.Boolean => new Variant(ic.ToBoolean(provider)), + TypeCode.Char => new Variant(ic.ToChar(provider)), + TypeCode.SByte => new Variant(ic.ToSByte(provider)), + TypeCode.Byte => new Variant(ic.ToByte(provider)), + TypeCode.Int16 => new Variant(ic.ToInt16(provider)), + TypeCode.UInt16 => new Variant(ic.ToUInt16(provider)), + TypeCode.Int32 => new Variant(ic.ToInt32(provider)), + TypeCode.UInt32 => new Variant(ic.ToUInt32(provider)), + TypeCode.Int64 => new Variant(ic.ToInt64(provider)), + TypeCode.UInt64 => new Variant(ic.ToUInt64(provider)), + TypeCode.Single => new Variant(ic.ToSingle(provider)), + TypeCode.Double => new Variant(ic.ToDouble(provider)), + TypeCode.Decimal => new Variant(ic.ToDecimal(provider)), + TypeCode.DateTime => new Variant(ic.ToDateTime(provider)), + TypeCode.String => new Variant(ic.ToString(provider)), + _ => throw new NotSupportedException(SR.Format(SR.NotSupported_UnknownTypeCode, ic.GetTypeCode())), + }; + } + else { // This path should eventually go away. But until // the work is done to have all of our wrapper types implement // IConvertible, this is a cheapo way to get the work done. v = new Variant(o); } - else - { - IFormatProvider provider = CultureInfo.InvariantCulture; - switch (ic.GetTypeCode()) - { - case TypeCode.Empty: - v = Empty; - break; - - case TypeCode.Object: - v = new Variant((object)o); - break; - - case TypeCode.DBNull: - v = DBNull; - break; - - case TypeCode.Boolean: - v = new Variant(ic.ToBoolean(provider)); - break; - - case TypeCode.Char: - v = new Variant(ic.ToChar(provider)); - break; - - case TypeCode.SByte: - v = new Variant(ic.ToSByte(provider)); - break; - - case TypeCode.Byte: - v = new Variant(ic.ToByte(provider)); - break; - - case TypeCode.Int16: - v = new Variant(ic.ToInt16(provider)); - break; - - case TypeCode.UInt16: - v = new Variant(ic.ToUInt16(provider)); - break; - - case TypeCode.Int32: - v = new Variant(ic.ToInt32(provider)); - break; - - case TypeCode.UInt32: - v = new Variant(ic.ToUInt32(provider)); - break; - - case TypeCode.Int64: - v = new Variant(ic.ToInt64(provider)); - break; - - case TypeCode.UInt64: - v = new Variant(ic.ToUInt64(provider)); - break; - - case TypeCode.Single: - v = new Variant(ic.ToSingle(provider)); - break; - - case TypeCode.Double: - v = new Variant(ic.ToDouble(provider)); - break; - - case TypeCode.Decimal: - v = new Variant(ic.ToDecimal(provider)); - break; - - case TypeCode.DateTime: - v = new Variant(ic.ToDateTime(provider)); - break; - - case TypeCode.String: - v = new Variant(ic.ToString(provider)); - break; - - default: - throw new NotSupportedException(SR.Format(SR.NotSupported_UnknownTypeCode, ic.GetTypeCode())); - } - } } // Helper code for marshaling VARIANTS to managed objects (we use @@ -530,106 +473,34 @@ internal static void MarshalHelperCastVariant(object pValue, int vt, ref Variant else { IFormatProvider provider = CultureInfo.InvariantCulture; - switch (vt) + v = vt switch { - case 0: /*VT_EMPTY*/ - v = Empty; - break; - - case 1: /*VT_NULL*/ - v = DBNull; - break; - - case 2: /*VT_I2*/ - v = new Variant(iv.ToInt16(provider)); - break; - - case 3: /*VT_I4*/ - v = new Variant(iv.ToInt32(provider)); - break; - - case 4: /*VT_R4*/ - v = new Variant(iv.ToSingle(provider)); - break; - - case 5: /*VT_R8*/ - v = new Variant(iv.ToDouble(provider)); - break; - - case 6: /*VT_CY*/ - v = new Variant(new CurrencyWrapper(iv.ToDecimal(provider))); - break; - - case 7: /*VT_DATE*/ - v = new Variant(iv.ToDateTime(provider)); - break; - - case 8: /*VT_BSTR*/ - v = new Variant(iv.ToString(provider)); - break; - - case 9: /*VT_DISPATCH*/ - v = new Variant(new DispatchWrapper((object)iv)); - break; - - case 10: /*VT_ERROR*/ - v = new Variant(new ErrorWrapper(iv.ToInt32(provider))); - break; - - case 11: /*VT_BOOL*/ - v = new Variant(iv.ToBoolean(provider)); - break; - - case 12: /*VT_VARIANT*/ - v = new Variant((object)iv); - break; - - case 13: /*VT_UNKNOWN*/ - v = new Variant(new UnknownWrapper((object)iv)); - break; - - case 14: /*VT_DECIMAL*/ - v = new Variant(iv.ToDecimal(provider)); - break; - - // case 15: /*unused*/ - // NOT SUPPORTED - - case 16: /*VT_I1*/ - v = new Variant(iv.ToSByte(provider)); - break; - - case 17: /*VT_UI1*/ - v = new Variant(iv.ToByte(provider)); - break; - - case 18: /*VT_UI2*/ - v = new Variant(iv.ToUInt16(provider)); - break; - - case 19: /*VT_UI4*/ - v = new Variant(iv.ToUInt32(provider)); - break; - - case 20: /*VT_I8*/ - v = new Variant(iv.ToInt64(provider)); - break; - - case 21: /*VT_UI8*/ - v = new Variant(iv.ToUInt64(provider)); - break; - - case 22: /*VT_INT*/ - v = new Variant(iv.ToInt32(provider)); - break; - - case 23: /*VT_UINT*/ - v = new Variant(iv.ToUInt32(provider)); - break; - - default: - throw new InvalidCastException(SR.InvalidCast_CannotCoerceByRefVariant); - } + 0 => /*VT_EMPTY*/ Empty, + 1 => /*VT_NULL*/ DBNull, + 2 => /*VT_I2*/ new Variant(iv.ToInt16(provider)), + 3 => /*VT_I4*/ new Variant(iv.ToInt32(provider)), + 4 => /*VT_R4*/ new Variant(iv.ToSingle(provider)), + 5 => /*VT_R8*/ new Variant(iv.ToDouble(provider)), + 6 => /*VT_CY*/ new Variant(new CurrencyWrapper(iv.ToDecimal(provider))), + 7 => /*VT_DATE*/ new Variant(iv.ToDateTime(provider)), + 8 => /*VT_BSTR*/ new Variant(iv.ToString(provider)), + 9 => /*VT_DISPATCH*/ new Variant(new DispatchWrapper((object)iv)), + 10 => /*VT_ERROR*/ new Variant(new ErrorWrapper(iv.ToInt32(provider))), + 11 => /*VT_BOOL*/ new Variant(iv.ToBoolean(provider)), + 12 => /*VT_VARIANT*/ new Variant((object)iv), + 13 => /*VT_UNKNOWN*/ new Variant(new UnknownWrapper((object)iv)), + 14 => /*VT_DECIMAL*/ new Variant(iv.ToDecimal(provider)), + // 15 => : /*unused*/ NOT SUPPORTED + 16 => /*VT_I1*/ new Variant(iv.ToSByte(provider)), + 17 => /*VT_UI1*/ new Variant(iv.ToByte(provider)), + 18 => /*VT_UI2*/ new Variant(iv.ToUInt16(provider)), + 19 => /*VT_UI4*/ new Variant(iv.ToUInt32(provider)), + 20 => /*VT_I8*/ new Variant(iv.ToInt64(provider)), + 21 => /*VT_UI8*/ new Variant(iv.ToUInt64(provider)), + 22 => /*VT_INT*/ new Variant(iv.ToInt32(provider)), + 23 => /*VT_UINT*/ new Variant(iv.ToUInt32(provider)), + _ => throw new InvalidCastException(SR.InvalidCast_CannotCoerceByRefVariant), + }; } } } From d7bf7fe35aeac7be72c30e433a15972a40602cc3 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Fri, 9 Aug 2019 13:53:24 -0400 Subject: [PATCH 3/6] Contribute to IDE0059 (unnecessary assignment) --- .../shared/System/Buffers/ConfigurableArrayPool.cs | 2 +- .../Text/Utf8Formatter/Utf8Formatter.Date.O.cs | 2 +- .../Text/Utf8Formatter/Utf8Formatter.Guid.cs | 10 +++++----- .../Collections/Concurrent/ConcurrentQueue.cs | 3 +-- .../shared/System/CurrentSystemTimeZone.cs | 2 +- .../shared/System/DateTime.cs | 2 +- .../shared/System/Delegate.cs | 2 +- .../System/Diagnostics/Tracing/EventSource.cs | 4 +--- .../System/Globalization/DateTimeFormatInfo.cs | 3 ++- .../shared/System/Globalization/TimeSpanParse.cs | 13 +++++-------- .../Resources/ManifestBasedResourceGroveler.cs | 2 +- .../shared/System/SpanHelpers.Byte.cs | 7 +------ .../shared/System/String.Manipulation.cs | 2 -- .../shared/System/Threading/Tasks/FutureFactory.cs | 2 +- .../shared/System/Threading/Tasks/Task.cs | 3 ++- .../shared/System/Threading/Tasks/TaskScheduler.cs | 2 +- .../shared/System/Threading/ThreadPool.cs | 5 ++--- .../WindowsRuntime/WindowsRuntimeMarshal.cs | 2 +- 18 files changed, 28 insertions(+), 40 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/Buffers/ConfigurableArrayPool.cs b/src/System.Private.CoreLib/shared/System/Buffers/ConfigurableArrayPool.cs index 054a38fc6028..f70edf110b99 100644 --- a/src/System.Private.CoreLib/shared/System/Buffers/ConfigurableArrayPool.cs +++ b/src/System.Private.CoreLib/shared/System/Buffers/ConfigurableArrayPool.cs @@ -74,7 +74,7 @@ public override T[] Rent(int minimumLength) } var log = ArrayPoolEventSource.Log; - T[]? buffer = null; + T[]? buffer; int index = Utilities.SelectBucketIndex(minimumLength); if (index < _buckets.Length) diff --git a/src/System.Private.CoreLib/shared/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.O.cs b/src/System.Private.CoreLib/shared/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.O.cs index d9b7b181bc44..6c6270b117a1 100644 --- a/src/System.Private.CoreLib/shared/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.O.cs +++ b/src/System.Private.CoreLib/shared/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.O.cs @@ -49,7 +49,7 @@ private static bool TryFormatDateTimeO(DateTime value, TimeSpan offset, Span destination, out int bytesWr // because it may have an observable side effect (throwing). // We use 8 instead of 7 so that we also capture the dash if we're asked to insert one. - { var unused = destination[8]; } + { _ = destination[8]; } FormattingHelpers.WriteHexByte(guidAsBytes.Byte03, destination, 0, FormattingHelpers.HexCasing.Lowercase); FormattingHelpers.WriteHexByte(guidAsBytes.Byte02, destination, 2, FormattingHelpers.HexCasing.Lowercase); FormattingHelpers.WriteHexByte(guidAsBytes.Byte01, destination, 4, FormattingHelpers.HexCasing.Lowercase); @@ -133,7 +133,7 @@ public static bool TryFormat(Guid value, Span destination, out int bytesWr destination = destination.Slice(8); } - { var unused = destination[4]; } + { _ = destination[4]; } FormattingHelpers.WriteHexByte(guidAsBytes.Byte05, destination, 0, FormattingHelpers.HexCasing.Lowercase); FormattingHelpers.WriteHexByte(guidAsBytes.Byte04, destination, 2, FormattingHelpers.HexCasing.Lowercase); @@ -147,7 +147,7 @@ public static bool TryFormat(Guid value, Span destination, out int bytesWr destination = destination.Slice(4); } - { var unused = destination[4]; } + { _ = destination[4]; } FormattingHelpers.WriteHexByte(guidAsBytes.Byte07, destination, 0, FormattingHelpers.HexCasing.Lowercase); FormattingHelpers.WriteHexByte(guidAsBytes.Byte06, destination, 2, FormattingHelpers.HexCasing.Lowercase); @@ -161,7 +161,7 @@ public static bool TryFormat(Guid value, Span destination, out int bytesWr destination = destination.Slice(4); } - { var unused = destination[4]; } + { _ = destination[4]; } FormattingHelpers.WriteHexByte(guidAsBytes.Byte08, destination, 0, FormattingHelpers.HexCasing.Lowercase); FormattingHelpers.WriteHexByte(guidAsBytes.Byte09, destination, 2, FormattingHelpers.HexCasing.Lowercase); @@ -175,7 +175,7 @@ public static bool TryFormat(Guid value, Span destination, out int bytesWr destination = destination.Slice(4); } - { var unused = destination[11]; } // can't hoist bounds check on the final brace (if exists) + { _ = destination[11]; } // can't hoist bounds check on the final brace (if exists) FormattingHelpers.WriteHexByte(guidAsBytes.Byte10, destination, 0, FormattingHelpers.HexCasing.Lowercase); FormattingHelpers.WriteHexByte(guidAsBytes.Byte11, destination, 2, FormattingHelpers.HexCasing.Lowercase); FormattingHelpers.WriteHexByte(guidAsBytes.Byte12, destination, 4, FormattingHelpers.HexCasing.Lowercase); diff --git a/src/System.Private.CoreLib/shared/System/Collections/Concurrent/ConcurrentQueue.cs b/src/System.Private.CoreLib/shared/System/Collections/Concurrent/ConcurrentQueue.cs index fd8c9753ebde..39e77904b3b3 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/Concurrent/ConcurrentQueue.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/Concurrent/ConcurrentQueue.cs @@ -218,8 +218,7 @@ public bool IsEmpty // IsEmpty == !TryPeek. We use a "resultUsed:false" peek in order to avoid marking // segments as preserved for observation, making IsEmpty a cheaper way than either // TryPeek(out T) or Count == 0 to check whether any elements are in the queue. - T ignoredResult; - return !TryPeek(out ignoredResult, resultUsed: false); + return !TryPeek(out _, resultUsed: false); } } diff --git a/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs b/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs index 285dcba29be3..8cf6674e0e62 100644 --- a/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs +++ b/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs @@ -89,7 +89,7 @@ internal long GetUtcOffsetFromUniversalTime(DateTime time, ref bool isAmbiguousL ambiguousEnd = startTime - daylightTime.Delta; } - bool isDst = false; + bool isDst; if (startTime > endTime) { // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year. diff --git a/src/System.Private.CoreLib/shared/System/DateTime.cs b/src/System.Private.CoreLib/shared/System/DateTime.cs index 6cb1c1ecfc8a..2f705c42b352 100644 --- a/src/System.Private.CoreLib/shared/System/DateTime.cs +++ b/src/System.Private.CoreLib/shared/System/DateTime.cs @@ -1110,7 +1110,7 @@ public static DateTime Now get { DateTime utc = UtcNow; - bool isAmbiguousLocalDst = false; + bool isAmbiguousLocalDst; long offset = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utc, out isAmbiguousLocalDst).Ticks; long tick = utc.Ticks + offset; if (tick > DateTime.MaxTicks) diff --git a/src/System.Private.CoreLib/shared/System/Delegate.cs b/src/System.Private.CoreLib/shared/System/Delegate.cs index 4e084d15425b..63aa97b8d649 100644 --- a/src/System.Private.CoreLib/shared/System/Delegate.cs +++ b/src/System.Private.CoreLib/shared/System/Delegate.cs @@ -82,7 +82,7 @@ public abstract partial class Delegate : ICloneable, ISerializable public static Delegate? RemoveAll(Delegate? source, Delegate? value) { - Delegate? newDelegate = null; + Delegate? newDelegate; do { diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs index 771b5f1ff749..1866d73cf344 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs @@ -672,9 +672,7 @@ protected EventSource(EventSourceSettings settings, params string[]? traits) Guid eventSourceGuid; string? eventSourceName; - EventMetadata[]? eventDescriptors; - byte[]? manifest; - GetMetadata(out eventSourceGuid, out eventSourceName, out eventDescriptors, out manifest); + GetMetadata(out eventSourceGuid, out eventSourceName, out _, out _); if (eventSourceGuid.Equals(Guid.Empty) || eventSourceName == null) { diff --git a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs index 07327ff902d8..fb2866613f29 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs @@ -2250,8 +2250,9 @@ internal TokenHashValue[] CreateTokenHashTable() // We need to rescan the date words since we're always synthetic DateTimeFormatInfoScanner scanner = new DateTimeFormatInfoScanner(); string[]? dateWords = scanner.GetDateWordsOfDTFI(this); + // Ensure the formatflags is initialized. - DateTimeFormatFlags flag = FormatFlags; + _ = FormatFlags; // For some cultures, the date separator works more like a comma, being allowed before or after any date part. // In these cultures, we do not use normal date separator since we disallow date separator after a date terminal state. diff --git a/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs b/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs index 4f492b755efb..c9e97d6a89b5 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs @@ -1120,7 +1120,7 @@ private static bool ProcessTerminal_HM(ref TimeSpanRawInfo raw, TimeSpanStandard if (match) { - long ticks = 0; + long ticks; var zero = new TimeSpanToken(0); if (!TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, zero, zero, out ticks)) @@ -1190,7 +1190,7 @@ private static bool ProcessTerminal_D(ref TimeSpanRawInfo raw, TimeSpanStandardS if (match) { - long ticks = 0; + long ticks; var zero = new TimeSpanToken(0); if (!TryTimeToTicks(positive, raw._numbers0, zero, zero, zero, zero, out ticks)) @@ -1261,7 +1261,7 @@ private static bool TryParseByFormat(ReadOnlySpan input, ReadOnlySpan input, ReadOnlySpan 8 || seenDD || !ParseExactDigits(ref tokenizer, (tokenLen < 2) ? 1 : tokenLen, (tokenLen < 2) ? 8 : tokenLen, out tmp, out dd)) + if (tokenLen > 8 || seenDD || !ParseExactDigits(ref tokenizer, (tokenLen < 2) ? 1 : tokenLen, (tokenLen < 2) ? 8 : tokenLen, out _, out dd)) { return result.SetInvalidStringFailure(); } @@ -1417,10 +1416,8 @@ private static bool TryParseByFormat(ReadOnlySpan input, ReadOnlySpan so we compare to ushort.MaxValue to check if everything matched - if (matches == ushort.MaxValue) - { - // All matched - offset += Vector128.Count; - } - else + if (matches != ushort.MaxValue) { goto Difference; } diff --git a/src/System.Private.CoreLib/shared/System/String.Manipulation.cs b/src/System.Private.CoreLib/shared/System/String.Manipulation.cs index 4ccb37ebdb49..f9cac8c0cdc1 100644 --- a/src/System.Private.CoreLib/shared/System/String.Manipulation.cs +++ b/src/System.Private.CoreLib/shared/System/String.Manipulation.cs @@ -1611,8 +1611,6 @@ private void MakeSeparatorList(string?[] separators, ref ValueListBuilder s { Debug.Assert(separators != null && separators.Length > 0, "separators != null && separators.Length > 0"); - int sepCount = separators.Length; - for (int i = 0; i < Length; i++) { for (int j = 0; j < separators.Length; j++) diff --git a/src/System.Private.CoreLib/shared/System/Threading/Tasks/FutureFactory.cs b/src/System.Private.CoreLib/shared/System/Threading/Tasks/FutureFactory.cs index 8ad7a5a85685..d0ae44272321 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/Tasks/FutureFactory.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/Tasks/FutureFactory.cs @@ -1288,7 +1288,7 @@ internal void Complete( Debug.Assert(!IsCompleted, "The task should not have been completed yet."); // Run the end method and complete the task - bool successfullySet = false; + bool successfullySet; try { var result = endMethod(thisRef, asyncResult); diff --git a/src/System.Private.CoreLib/shared/System/Threading/Tasks/Task.cs b/src/System.Private.CoreLib/shared/System/Threading/Tasks/Task.cs index c1a5ac3ed9fb..7257d9a8b696 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/Tasks/Task.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/Tasks/Task.cs @@ -1168,7 +1168,8 @@ internal static Task InternalStartNew( /// internal static int NewId() { - int newId = 0; + int newId; + // We need to repeat if Interlocked.Increment wraps around and returns 0. // Otherwise next time this task's Id is queried it will get a new value do diff --git a/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskScheduler.cs b/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskScheduler.cs index 75b8cab3ec32..0ad671c4fef0 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskScheduler.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/Tasks/TaskScheduler.cs @@ -377,7 +377,7 @@ public int Id { if (m_taskSchedulerId == 0) { - int newId = 0; + int newId; // We need to repeat if Interlocked.Increment wraps around and returns 0. // Otherwise next time this scheduler's Id is queried it will get a new value diff --git a/src/System.Private.CoreLib/shared/System/Threading/ThreadPool.cs b/src/System.Private.CoreLib/shared/System/Threading/ThreadPool.cs index 6925af04265f..fae558441156 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/ThreadPool.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/ThreadPool.cs @@ -582,7 +582,6 @@ internal static bool Dispatch() // false later, but only if we're absolutely certain that the queue is empty. // bool needAnotherThread = true; - object? outerWorkItem = null; try { // @@ -604,7 +603,7 @@ internal static bool Dispatch() { bool missedSteal = false; // Use operate on workItem local to try block so it can be enregistered - object? workItem = outerWorkItem = workQueue.Dequeue(tl, ref missedSteal); + object? workItem = workQueue.Dequeue(tl, ref missedSteal); if (workItem == null) { @@ -673,7 +672,7 @@ internal static bool Dispatch() currentThread.ResetThreadPoolThread(); // Release refs - outerWorkItem = workItem = null; + workItem = null; // Return to clean ExecutionContext and SynchronizationContext ExecutionContext.ResetThreadPoolThread(currentThread); diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs index 9a009c86e62a..e3a987e88e68 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs @@ -1061,7 +1061,7 @@ internal static unsafe string HStringToString(IntPtr hstring) internal static Exception GetExceptionForHR(int hresult, Exception? innerException, string? messageResource) { - Exception? e = null; + Exception? e; if (innerException != null) { string? message = innerException.Message; From 9076a2d24853f1ab1c3f0edd0794dd47bb2be112 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Fri, 9 Aug 2019 14:59:12 -0400 Subject: [PATCH 4/6] Contribute to IDE0060 (unused argument) --- .../System/Diagnostics/Tracing/EventSource.cs | 9 ++++----- .../TraceLogging/TraceLoggingEventSource.cs | 2 +- .../System/Globalization/DateTimeFormat.cs | 18 ++---------------- .../shared/System/Number.Formatting.cs | 10 +++++----- 4 files changed, 12 insertions(+), 27 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs index 1866d73cf344..47ee18f7c865 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs @@ -2149,10 +2149,10 @@ internal unsafe void WriteToAllListeners(int eventId, uint* osThreadId, DateTime eventCallbackArgs.Message = m_eventData[eventId].Message; eventCallbackArgs.Payload = new ReadOnlyCollection(args); - DispatchToAllListeners(eventId, childActivityID, eventCallbackArgs); + DispatchToAllListeners(eventId, eventCallbackArgs); } - private unsafe void DispatchToAllListeners(int eventId, Guid* childActivityID, EventWrittenEventArgs eventCallbackArgs) + private unsafe void DispatchToAllListeners(int eventId, EventWrittenEventArgs eventCallbackArgs) { Exception? lastThrownException = null; for (EventDispatcher? dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) @@ -5897,7 +5897,7 @@ private string CreateManifestString() List? cultures = null; if (resources != null && (flags & EventManifestOptions.AllCultures) != 0) { - cultures = GetSupportedCultures(resources); + cultures = GetSupportedCultures(); } else { @@ -5984,9 +5984,8 @@ private void WriteMessageAttrib(StringBuilder stringBuilder, string elementName, /// we enumerate through all the "known" cultures and attempt to load a corresponding satellite /// assembly /// - /// /// - private static List GetSupportedCultures(ResourceManager resources) + private static List GetSupportedCultures() { var cultures = new List(); diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs index 68c758e17ee1..57f2637f207e 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs @@ -743,7 +743,7 @@ private unsafe void WriteToAllListeners(string? eventName, ref EventDescriptor e eventCallbackArgs.PayloadNames = new ReadOnlyCollection((IList)payload.Keys); } - DispatchToAllListeners(-1, pActivityId, eventCallbackArgs); + DispatchToAllListeners(-1, eventCallbackArgs); } #if (!ES_BUILD_PCL && !ES_BUILD_PN) diff --git a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormat.cs b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormat.cs index 6f6d10ab94a7..55d40398eca5 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormat.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormat.cs @@ -689,7 +689,7 @@ private static StringBuilder FormatCustomized( break; case 'z': tokenLen = ParseRepeatPattern(format, i, ch); - FormatCustomizedTimeZone(dateTime, offset, format, tokenLen, bTimeOnly, result); + FormatCustomizedTimeZone(dateTime, offset, tokenLen, bTimeOnly, result); break; case 'K': tokenLen = 1; @@ -777,7 +777,7 @@ private static StringBuilder FormatCustomized( // output the 'z' famliy of formats, which output a the offset from UTC, e.g. "-07:30" - private static void FormatCustomizedTimeZone(DateTime dateTime, TimeSpan offset, ReadOnlySpan format, int tokenLen, bool timeOnly, StringBuilder result) + private static void FormatCustomizedTimeZone(DateTime dateTime, TimeSpan offset, int tokenLen, bool timeOnly, StringBuilder result) { // See if the instance already has an offset bool dateTimeFormat = (offset == NullOffset); @@ -958,10 +958,6 @@ private static string ExpandPredefinedFormat(ReadOnlySpan format, ref Date // Convert to UTC invariants mean this will be in range dateTime = dateTime - offset; } - else if (dateTime.Kind == DateTimeKind.Local) - { - InvalidFormatForLocal(format, dateTime); - } dtfi = DateTimeFormatInfo.InvariantInfo; break; case 's': // Sortable without Time Zone Info @@ -973,10 +969,6 @@ private static string ExpandPredefinedFormat(ReadOnlySpan format, ref Date // Convert to UTC invariants mean this will be in range dateTime = dateTime - offset; } - else if (dateTime.Kind == DateTimeKind.Local) - { - InvalidFormatForLocal(format, dateTime); - } dtfi = DateTimeFormatInfo.InvariantInfo; break; case 'U': // Universal time in culture dependent format. @@ -1394,11 +1386,5 @@ internal static string[] GetAllDateTimes(DateTime dateTime, DateTimeFormatInfo d return results.ToArray(); } - - // This is a placeholder for an MDA to detect when the user is using a - // local DateTime with a format that will be interpreted as UTC. - internal static void InvalidFormatForLocal(ReadOnlySpan format, DateTime dateTime) - { - } } } diff --git a/src/System.Private.CoreLib/shared/System/Number.Formatting.cs b/src/System.Private.CoreLib/shared/System/Number.Formatting.cs index 2d3c2228f69b..70e893471342 100644 --- a/src/System.Private.CoreLib/shared/System/Number.Formatting.cs +++ b/src/System.Private.CoreLib/shared/System/Number.Formatting.cs @@ -1633,7 +1633,7 @@ internal static unsafe void NumberToString(ref ValueStringBuilder sb, ref Number if (number.IsNegative) sb.Append(info.NegativeSign); - FormatFixed(ref sb, ref number, nMaxDigits, info, null, info.NumberDecimalSeparator, null); + FormatFixed(ref sb, ref number, nMaxDigits, null, info.NumberDecimalSeparator, null); break; } @@ -2115,7 +2115,7 @@ private static void FormatCurrency(ref ValueStringBuilder sb, ref NumberBuffer n switch (ch) { case '#': - FormatFixed(ref sb, ref number, nMaxDigits, info, info._currencyGroupSizes, info.CurrencyDecimalSeparator, info.CurrencyGroupSeparator); + FormatFixed(ref sb, ref number, nMaxDigits, info._currencyGroupSizes, info.CurrencyDecimalSeparator, info.CurrencyGroupSeparator); break; case '-': sb.Append(info.NegativeSign); @@ -2130,7 +2130,7 @@ private static void FormatCurrency(ref ValueStringBuilder sb, ref NumberBuffer n } } - private static unsafe void FormatFixed(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, NumberFormatInfo? info, int[]? groupDigits, string? sDecimal, string? sGroup) + private static unsafe void FormatFixed(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, int[]? groupDigits, string? sDecimal, string? sGroup) { int digPos = number.Scale; byte* dig = number.GetDigitsPointer(); @@ -2245,7 +2245,7 @@ private static void FormatNumber(ref ValueStringBuilder sb, ref NumberBuffer num switch (ch) { case '#': - FormatFixed(ref sb, ref number, nMaxDigits, info, info._numberGroupSizes, info.NumberDecimalSeparator, info.NumberGroupSeparator); + FormatFixed(ref sb, ref number, nMaxDigits, info._numberGroupSizes, info.NumberDecimalSeparator, info.NumberGroupSeparator); break; case '-': sb.Append(info.NegativeSign); @@ -2352,7 +2352,7 @@ private static void FormatPercent(ref ValueStringBuilder sb, ref NumberBuffer nu switch (ch) { case '#': - FormatFixed(ref sb, ref number, nMaxDigits, info, info._percentGroupSizes, info.PercentDecimalSeparator, info.PercentGroupSeparator); + FormatFixed(ref sb, ref number, nMaxDigits, info._percentGroupSizes, info.PercentDecimalSeparator, info.PercentGroupSeparator); break; case '-': sb.Append(info.NegativeSign); From 2e17ae4d532ca543cd38e1e6e45509fa9a0f35c8 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Fri, 9 Aug 2019 15:15:07 -0400 Subject: [PATCH 5/6] Fix IDE0062 (make local functions static) --- .../shared/System/ComponentModel/DefaultValueAttribute.cs | 2 +- .../shared/System/Globalization/ISOWeek.cs | 2 +- .../shared/System/Globalization/NumberFormatInfo.cs | 2 +- src/System.Private.CoreLib/shared/System/IO/Stream.cs | 2 +- src/System.Private.CoreLib/shared/System/Number.Formatting.cs | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs b/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs index 423436e34c86..428464c6c0ba 100644 --- a/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs @@ -60,7 +60,7 @@ public DefaultValueAttribute(Type type, string? value) } // Looking for ad hoc created TypeDescriptor.ConvertFromInvariantString(Type, string) - bool TryConvertFromInvariantString(Type? typeToConvert, string? stringValue, out object? conversionResult) + static bool TryConvertFromInvariantString(Type? typeToConvert, string? stringValue, out object? conversionResult) { conversionResult = null; diff --git a/src/System.Private.CoreLib/shared/System/Globalization/ISOWeek.cs b/src/System.Private.CoreLib/shared/System/Globalization/ISOWeek.cs index 60715713b195..e5b122e45018 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/ISOWeek.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/ISOWeek.cs @@ -90,7 +90,7 @@ public static int GetWeeksInYear(int year) throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_Year); } - int P(int y) => (y + (y / 4) - (y / 100) + (y / 400)) % 7; + static int P(int y) => (y + (y / 4) - (y / 100) + (y / 400)) % 7; if (P(year) == 4 || P(year - 1) == 3) { diff --git a/src/System.Private.CoreLib/shared/System/Globalization/NumberFormatInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/NumberFormatInfo.cs index 7af038162fc0..3a508cd459ae 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/NumberFormatInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/NumberFormatInfo.cs @@ -211,7 +211,7 @@ public static NumberFormatInfo GetInstance(IFormatProvider? formatProvider) CurrentInfo : // Fast path for a null provider GetProviderNonNull(formatProvider); - NumberFormatInfo GetProviderNonNull(IFormatProvider provider) + static NumberFormatInfo GetProviderNonNull(IFormatProvider provider) { // Fast path for a regular CultureInfo if (provider is CultureInfo cultureProvider && !cultureProvider._isInherited) diff --git a/src/System.Private.CoreLib/shared/System/IO/Stream.cs b/src/System.Private.CoreLib/shared/System/IO/Stream.cs index 6910689ee31b..d1347d9f66c0 100644 --- a/src/System.Private.CoreLib/shared/System/IO/Stream.cs +++ b/src/System.Private.CoreLib/shared/System/IO/Stream.cs @@ -387,7 +387,7 @@ public virtual ValueTask ReadAsync(Memory buffer, CancellationToken c byte[] sharedBuffer = ArrayPool.Shared.Rent(buffer.Length); return FinishReadAsync(ReadAsync(sharedBuffer, 0, buffer.Length, cancellationToken), sharedBuffer, buffer); - async ValueTask FinishReadAsync(Task readTask, byte[] localBuffer, Memory localDestination) + static async ValueTask FinishReadAsync(Task readTask, byte[] localBuffer, Memory localDestination) { try { diff --git a/src/System.Private.CoreLib/shared/System/Number.Formatting.cs b/src/System.Private.CoreLib/shared/System/Number.Formatting.cs index 70e893471342..fce06ac2f025 100644 --- a/src/System.Private.CoreLib/shared/System/Number.Formatting.cs +++ b/src/System.Private.CoreLib/shared/System/Number.Formatting.cs @@ -2411,7 +2411,7 @@ internal static unsafe void RoundNumber(ref NumberBuffer number, int pos, bool i number.DigitsCount = i; number.CheckConsistency(); - bool ShouldRoundUp(byte* dig, int i, NumberBufferKind numberKind, bool isCorrectlyRounded) + static bool ShouldRoundUp(byte* dig, int i, NumberBufferKind numberKind, bool isCorrectlyRounded) { // We only want to round up if the digit is greater than or equal to 5 and we are // not rounding a floating-point number. If we are rounding a floating-point number From bd92f17a9d535c5ac12c7030a6714a41e9c721f4 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Fri, 9 Aug 2019 15:18:50 -0400 Subject: [PATCH 6/6] Fix IDE1005 (simplify delegate invocation) --- .../System/Diagnostics/Tracing/EventSource.cs | 14 +++----------- .../shared/System/IO/Stream.cs | 10 ++-------- .../shared/System/Progress.cs | 4 ++-- 3 files changed, 7 insertions(+), 21 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs index 47ee18f7c865..df40519728cd 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs @@ -2782,9 +2782,7 @@ internal void DoCommand(EventCommandEventArgs commandArgs) } this.OnEventCommand(commandArgs); - var eventCommandCallback = this.m_eventCommandExecuted; - if (eventCommandCallback != null) - eventCommandCallback(this, commandArgs); + this.m_eventCommandExecuted?.Invoke(this, commandArgs); if (!commandArgs.enable) { @@ -2835,9 +2833,7 @@ internal void DoCommand(EventCommandEventArgs commandArgs) // Debug.Assert(matchAnyKeyword == EventKeywords.None); this.OnEventCommand(commandArgs); - var eventCommandCallback = m_eventCommandExecuted; - if (eventCommandCallback != null) - eventCommandCallback(this, commandArgs); + m_eventCommandExecuted?.Invoke(this, commandArgs); } } catch (Exception e) @@ -4255,11 +4251,7 @@ protected internal virtual void OnEventSourceCreated(EventSource eventSource) /// protected internal virtual void OnEventWritten(EventWrittenEventArgs eventData) { - EventHandler? callBack = this.EventWritten; - if (callBack != null) - { - callBack(this, eventData); - } + this.EventWritten?.Invoke(this, eventData); } diff --git a/src/System.Private.CoreLib/shared/System/IO/Stream.cs b/src/System.Private.CoreLib/shared/System/IO/Stream.cs index d1347d9f66c0..d02f2503dbb4 100644 --- a/src/System.Private.CoreLib/shared/System/IO/Stream.cs +++ b/src/System.Private.CoreLib/shared/System/IO/Stream.cs @@ -829,10 +829,7 @@ internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, As asyncResult = new SynchronousAsyncResult(ex, state, isWrite: false); } - if (callback != null) - { - callback(asyncResult); - } + callback?.Invoke(asyncResult); return asyncResult; } @@ -861,10 +858,7 @@ internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, A asyncResult = new SynchronousAsyncResult(ex, state, isWrite: true); } - if (callback != null) - { - callback(asyncResult); - } + callback?.Invoke(asyncResult); return asyncResult; } diff --git a/src/System.Private.CoreLib/shared/System/Progress.cs b/src/System.Private.CoreLib/shared/System/Progress.cs index b6348bdb773c..e7535bcb9035 100644 --- a/src/System.Private.CoreLib/shared/System/Progress.cs +++ b/src/System.Private.CoreLib/shared/System/Progress.cs @@ -88,8 +88,8 @@ private void InvokeHandlers(object? state) Action? handler = _handler; EventHandler? changedEvent = ProgressChanged; - if (handler != null) handler(value); - if (changedEvent != null) changedEvent(this, value); + handler?.Invoke(value); + changedEvent?.Invoke(this, value); } }