From da8b7181dbe362fbfe64c7ef72ff3a4a7db68f24 Mon Sep 17 00:00:00 2001 From: Dan Moseley Date: Tue, 26 Sep 2017 14:19:16 -0700 Subject: [PATCH] Replace Contract.Assumes and Contract.Assert with Debug.Assert/Debug.Fail (#14136) * Remove use of Contract.Assert and Contract.Assumes in favor of Debug.xx * Remove dead IA64 blocks * Remove use of Contract.Requires in favor of Debug.Assert * Remove Contract.EndContractBlock() * Dead comments * Straggler EndcontractBlock * Remove all Contract.Ensures * Remove [Pure] attribute and using statements * Remove using statements for M.D.Contracts.Internal.Contract * Rmove CA suppressions for Contracts * Remove M.D.Contracts.Internal stub * Comments and extra using * Revert accidentallly removed #if * Unix build * Merge Math* * Fix assert not updated since desktop * Asserts add no value: remove * Avoid infinite recursion in StringBuilder assert * Remove asserts that should be public parameter validation * Fix comment * Remove blank line after open curly --- src/mscorlib/shared/System/Boolean.cs | 1 - src/mscorlib/shared/System/Byte.cs | 4 - src/mscorlib/shared/System/Char.cs | 25 -- .../System/Collections/Generic/ICollection.cs | 1 - .../System/Collections/Generic/IDictionary.cs | 1 - .../System/Collections/Generic/IEnumerable.cs | 1 - .../System/Collections/Generic/IList.cs | 1 - .../Generic/IReadOnlyCollection.cs | 1 - .../Generic/IReadOnlyDictionary.cs | 1 - .../Collections/Generic/IReadOnlyList.cs | 1 - .../shared/System/Collections/Generic/List.cs | 69 ----- .../shared/System/Collections/ICollection.cs | 1 - .../shared/System/Collections/IDictionary.cs | 1 - .../shared/System/Collections/IEnumerable.cs | 2 - .../shared/System/Collections/IList.cs | 1 - .../Collections/ListDictionaryInternal.cs | 8 - src/mscorlib/shared/System/Convert.cs | 110 -------- .../shared/System/CurrentSystemTimeZone.cs | 1 - src/mscorlib/shared/System/DateTime.cs | 49 ---- .../Diagnostics/Tracing/ActivityTracker.cs | 7 - .../Diagnostics/Tracing/EventDescriptor.cs | 6 - .../Diagnostics/Tracing/EventProvider.cs | 7 - .../System/Diagnostics/Tracing/EventSource.cs | 17 -- .../Diagnostics/Tracing/StubEnvironment.cs | 23 -- .../Tracing/TraceLogging/EventPayload.cs | 6 - .../TraceLogging/EventSourceActivity.cs | 7 - .../Tracing/TraceLogging/PropertyValue.cs | 6 - .../Tracing/TraceLogging/SimpleTypeInfos.cs | 6 - .../TraceLogging/TraceLoggingEventSource.cs | 5 - .../TraceLogging/TraceLoggingEventTypes.cs | 11 - .../TraceLogging/TraceLoggingTypeInfo.cs | 8 - src/mscorlib/shared/System/Double.cs | 13 - .../shared/System/Globalization/Calendar.cs | 5 - .../System/Globalization/CalendarData.Unix.cs | 1 - .../Globalization/ChineseLunisolarCalendar.cs | 3 - .../System/Globalization/CultureData.Unix.cs | 1 - .../System/Globalization/DateTimeFormat.cs | 5 +- .../Globalization/DateTimeFormatInfo.cs | 34 --- .../DateTimeFormatInfoScanner.cs | 1 - .../System/Globalization/DateTimeParse.cs | 8 - .../EastAsianLunisolarCalendar.cs | 6 - .../System/Globalization/GregorianCalendar.cs | 7 - .../Globalization/GregorianCalendarHelper.cs | 7 - .../System/Globalization/HebrewCalendar.cs | 2 - .../System/Globalization/HijriCalendar.cs | 5 - .../System/Globalization/JapaneseCalendar.cs | 3 - .../JapaneseLunisolarCalendar.cs | 2 - .../System/Globalization/JulianCalendar.cs | 3 - .../System/Globalization/KoreanCalendar.cs | 3 - .../Globalization/KoreanLunisolarCalendar.cs | 3 - .../System/Globalization/LocaleData.Unix.cs | 1 - .../System/Globalization/NumberFormatInfo.cs | 28 -- .../System/Globalization/PersianCalendar.cs | 3 - .../shared/System/Globalization/SortKey.cs | 2 - .../shared/System/Globalization/StringInfo.cs | 5 - .../System/Globalization/TaiwanCalendar.cs | 3 - .../Globalization/TaiwanLunisolarCalendar.cs | 2 - .../Globalization/ThaiBuddhistCalendar.cs | 3 - .../System/Globalization/UmAlQuraCalendar.cs | 4 - src/mscorlib/shared/System/Guid.cs | 3 - src/mscorlib/shared/System/IFormattable.cs | 2 - src/mscorlib/shared/System/IO/Error.cs | 2 - src/mscorlib/shared/System/IO/Path.cs | 9 - .../System/IO/PinnedBufferMemoryStream.cs | 1 - .../shared/System/IO/UnmanagedMemoryStream.cs | 11 - .../System/IO/UnmanagedMemoryStreamWrapper.cs | 4 - src/mscorlib/shared/System/Int16.cs | 7 - src/mscorlib/shared/System/Int32.cs | 16 -- src/mscorlib/shared/System/Int64.cs | 5 - src/mscorlib/shared/System/Math.cs | 16 +- src/mscorlib/shared/System/MathF.cs | 2 - .../System/Resources/RuntimeResourceSet.cs | 2 - .../Versioning/TargetFrameworkAttribute.cs | 2 - src/mscorlib/shared/System/SByte.cs | 7 - src/mscorlib/shared/System/Single.cs | 13 - src/mscorlib/shared/System/StringComparer.cs | 11 - .../shared/System/Text/ASCIIEncoding.cs | 14 - src/mscorlib/shared/System/Text/Decoder.cs | 6 - src/mscorlib/shared/System/Text/DecoderNLS.cs | 7 - .../System/Text/DecoderReplacementFallback.cs | 2 - src/mscorlib/shared/System/Text/Encoder.cs | 6 - .../System/Text/EncoderBestFitFallback.cs | 2 - .../System/Text/EncoderExceptionFallback.cs | 3 - src/mscorlib/shared/System/Text/EncoderNLS.cs | 7 - .../System/Text/EncoderReplacementFallback.cs | 3 - src/mscorlib/shared/System/Text/Encoding.cs | 55 ---- .../shared/System/Text/EncodingNLS.cs | 12 - .../shared/System/Text/Latin1Encoding.cs | 3 - .../shared/System/Text/StringBuilder.cs | 51 +--- .../shared/System/Text/UTF32Encoding.cs | 15 -- .../shared/System/Text/UTF7Encoding.cs | 14 - .../shared/System/Text/UTF8Encoding.cs | 14 - .../shared/System/Text/UnicodeEncoding.cs | 14 - .../System/Threading/ExecutionContext.cs | 4 - src/mscorlib/shared/System/TimeSpan.cs | 4 - src/mscorlib/shared/System/UInt16.cs | 5 - src/mscorlib/shared/System/UInt32.cs | 5 - src/mscorlib/shared/System/UInt64.cs | 5 - src/mscorlib/shared/System/ValueTuple.cs | 6 +- src/mscorlib/shared/System/Version.cs | 6 - src/mscorlib/src/Internal/Padding.cs | 1 - .../Runtime/Augments/RuntimeThread.cs | 1 - .../src/Microsoft/Win32/OAVariantLib.cs | 4 +- .../src/Microsoft/Win32/RegistryKey.cs | 5 +- src/mscorlib/src/System/Activator.cs | 3 - src/mscorlib/src/System/AppDomain.cs | 8 +- src/mscorlib/src/System/AppDomainSetup.cs | 2 - src/mscorlib/src/System/ArgIterator.cs | 1 - src/mscorlib/src/System/Array.cs | 145 +--------- src/mscorlib/src/System/ArraySegment.cs | 14 +- src/mscorlib/src/System/Attribute.cs | 39 +-- src/mscorlib/src/System/BCLDebug.cs | 5 - src/mscorlib/src/System/Buffer.cs | 1 - .../src/System/Collections/Comparer.cs | 2 - .../System/Collections/CompatibleComparer.cs | 2 - .../EmptyReadOnlyDictionaryInternal.cs | 5 - .../Collections/Generic/ArraySortHelper.cs | 255 +++++++++--------- .../System/Collections/Generic/Comparer.cs | 3 - .../System/Collections/Generic/Dictionary.cs | 3 - .../Collections/Generic/EqualityComparer.cs | 19 -- .../src/System/Collections/Hashtable.cs | 23 +- .../ObjectModel/ReadOnlyDictionary.cs | 4 - src/mscorlib/src/System/DateTime.CoreCLR.cs | 2 - src/mscorlib/src/System/Decimal.cs | 13 +- src/mscorlib/src/System/Delegate.cs | 9 - src/mscorlib/src/System/Diagnostics/Assert.cs | 1 - .../System/Diagnostics/Contracts/Contracts.cs | 4 - .../Diagnostics/Contracts/ContractsBCL.cs | 6 +- .../System/Diagnostics/DebuggerAttributes.cs | 5 - .../Diagnostics/Eventing/XplatEventLogger.cs | 4 - .../src/System/Diagnostics/LogSwitch.cs | 2 - .../src/System/Diagnostics/Stackframe.cs | 3 - .../src/System/Diagnostics/Stacktrace.cs | 7 - src/mscorlib/src/System/Diagnostics/log.cs | 2 - src/mscorlib/src/System/Empty.cs | 1 - src/mscorlib/src/System/Enum.cs | 31 +-- src/mscorlib/src/System/Environment.cs | 4 - src/mscorlib/src/System/Exception.cs | 3 - src/mscorlib/src/System/GC.cs | 7 - .../Globalization/CalendarData.Windows.cs | 1 - .../System/Globalization/CharUnicodeInfo.cs | 5 - .../Globalization/CompareInfo.Invariant.cs | 2 - .../System/Globalization/CompareInfo.Unix.cs | 2 - .../Globalization/CompareInfo.Windows.cs | 2 - .../src/System/Globalization/CompareInfo.cs | 25 +- .../src/System/Globalization/CultureInfo.cs | 27 -- .../Globalization/EncodingTable.Unix.cs | 2 - .../src/System/Globalization/EncodingTable.cs | 2 - .../src/System/Globalization/IdnMapping.cs | 9 +- .../src/System/Globalization/RegionInfo.cs | 2 - .../src/System/Globalization/TextInfo.Unix.cs | 1 - .../src/System/Globalization/TextInfo.cs | 3 - src/mscorlib/src/System/Guid.CoreCLR.cs | 8 - src/mscorlib/src/System/IO/BinaryReader.cs | 28 -- src/mscorlib/src/System/IO/Directory.cs | 23 +- src/mscorlib/src/System/IO/File.cs | 8 +- .../src/System/IO/FileSystemEnumerable.cs | 36 ++- src/mscorlib/src/System/IO/MemoryStream.cs | 19 -- src/mscorlib/src/System/IO/Stream.cs | 75 +----- src/mscorlib/src/System/IO/StreamReader.cs | 9 - src/mscorlib/src/System/IO/TextReader.cs | 39 +-- .../src/System/IO/UnmanagedMemoryAccessor.cs | 9 - src/mscorlib/src/System/IO/__Error.cs | 2 - src/mscorlib/src/System/IntPtr.cs | 6 - .../src/System/MissingMemberException.cs | 1 - src/mscorlib/src/System/MulticastDelegate.cs | 3 - src/mscorlib/src/System/Nullable.cs | 2 - src/mscorlib/src/System/Number.cs | 1 - src/mscorlib/src/System/Object.cs | 16 +- .../src/System/Reflection/Assembly.CoreCLR.cs | 16 -- .../src/System/Reflection/AssemblyName.cs | 3 - .../src/System/Reflection/Associates.cs | 1 - .../src/System/Reflection/CustomAttribute.cs | 98 ++++--- .../System/Reflection/Emit/AssemblyBuilder.cs | 16 +- .../Reflection/Emit/AssemblyBuilderData.cs | 1 - .../Reflection/Emit/ConstructorBuilder.cs | 2 - .../Reflection/Emit/CustomAttributeBuilder.cs | 2 - .../Reflection/Emit/DynamicILGenerator.cs | 12 - .../System/Reflection/Emit/DynamicMethod.cs | 7 - .../src/System/Reflection/Emit/EnumBuilder.cs | 4 - .../System/Reflection/Emit/EventBuilder.cs | 4 - .../System/Reflection/Emit/FieldBuilder.cs | 4 - .../src/System/Reflection/Emit/FlowControl.cs | 1 - .../Emit/GenericTypeParameterBuilder.cs | 3 - .../src/System/Reflection/Emit/ILGenerator.cs | 25 +- .../System/Reflection/Emit/MethodBuilder.cs | 12 - .../Emit/MethodBuilderInstantiation.cs | 3 - .../System/Reflection/Emit/ModuleBuilder.cs | 49 ---- .../Reflection/Emit/ModuleBuilderData.cs | 1 - .../src/System/Reflection/Emit/OpCodeType.cs | 1 - .../src/System/Reflection/Emit/OpCodes.cs | 2 - .../src/System/Reflection/Emit/Opcode.cs | 5 - .../src/System/Reflection/Emit/OperandType.cs | 1 - .../Reflection/Emit/ParameterBuilder.cs | 3 - .../System/Reflection/Emit/PropertyBuilder.cs | 2 - .../System/Reflection/Emit/SignatureHelper.cs | 5 +- .../System/Reflection/Emit/StackBehaviour.cs | 1 - .../System/Reflection/Emit/SymbolMethod.cs | 2 - .../src/System/Reflection/Emit/SymbolType.cs | 4 - .../src/System/Reflection/Emit/TypeBuilder.cs | 57 +--- .../Emit/TypeBuilderInstantiation.cs | 7 +- .../Emit/XXXOnTypeBuilderInstantiation.cs | 4 - .../Reflection/ExceptionHandlingClause.cs | 2 - .../src/System/Reflection/MdImport.cs | 4 +- .../src/System/Reflection/RtFieldInfo.cs | 3 - .../src/System/Reflection/RuntimeAssembly.cs | 6 - .../Reflection/RuntimeConstructorInfo.cs | 7 - .../src/System/Reflection/RuntimeEventInfo.cs | 7 +- .../src/System/Reflection/RuntimeFieldInfo.cs | 3 - .../System/Reflection/RuntimeMethodInfo.cs | 11 - .../src/System/Reflection/RuntimeModule.cs | 4 - .../System/Reflection/RuntimeParameterInfo.cs | 11 +- .../System/Reflection/RuntimePropertyInfo.cs | 13 +- .../Resources/FileBasedResourceGroveler.cs | 1 - .../ManifestBasedResourceGroveler.cs | 11 +- .../src/System/Resources/ResourceManager.cs | 9 - .../src/System/Resources/ResourceReader.cs | 25 +- .../src/System/Resources/ResourceSet.cs | 3 - .../Resources/__FastResourceComparer.cs | 1 - src/mscorlib/src/System/RtType.cs | 53 +--- .../CompilerServices/RuntimeHelpers.cs | 1 - .../Runtime/CompilerServices/TaskAwaiter.cs | 19 +- .../TypeDependencyAttribute.cs | 2 - .../CompilerServices/YieldAwaitable.cs | 2 - .../Runtime/CompilerServices/jithelpers.cs | 1 - src/mscorlib/src/System/Runtime/GcSettings.cs | 3 - .../Runtime/InteropServices/Attributes.cs | 1 - .../Runtime/InteropServices/GcHandle.cs | 3 - .../System/Runtime/InteropServices/Marshal.cs | 19 -- .../Runtime/InteropServices/SafeBuffer.cs | 5 - .../BindableVectorToCollectionAdapter.cs | 5 - .../BindableVectorToListAdapter.cs | 3 - .../WindowsRuntime/CLRIKeyValuePairImpl.cs | 8 +- .../WindowsRuntime/CLRIPropertyValueImpl.cs | 65 +---- .../WindowsRuntime/CLRIReferenceImpl.cs | 13 +- .../WindowsRuntime/ConstantSplittableMap.cs | 11 +- .../WindowsRuntime/CustomPropertyImpl.cs | 1 - .../WindowsRuntime/DictionaryToMapAdapter.cs | 1 - .../DictionaryValueCollection.cs | 1 - .../EnumeratorToIteratorAdapter.cs | 3 +- .../EventRegistrationTokenTable.cs | 6 +- .../WindowsRuntime/IClosable.cs | 1 - .../WindowsRuntime/ICustomProperty.cs | 7 - .../WindowsRuntime/ICustomPropertyProvider.cs | 24 +- .../WindowsRuntime/IIterable.cs | 3 - .../WindowsRuntime/IIterator.cs | 6 - .../InteropServices/WindowsRuntime/IMap.cs | 11 - .../IMapViewToIReadOnlyDictionaryAdapter.cs | 5 +- .../WindowsRuntime/IPropertyValue.cs | 40 --- .../IReadOnlyDictionaryToIMapViewAdapter.cs | 1 - .../IReadOnlyListToIVectorViewAdapter.cs | 1 - .../InteropServices/WindowsRuntime/IVector.cs | 21 -- .../IVectorViewToIReadOnlyListAdapter.cs | 1 - .../IteratorToEnumeratorAdapter.cs | 3 +- .../ListToBindableVectorAdapter.cs | 1 - .../ListToBindableVectorViewAdapter.cs | 2 - .../WindowsRuntime/ListToVectorAdapter.cs | 1 - .../ManagedActivationFactory.cs | 1 - .../WindowsRuntime/MapToCollectionAdapter.cs | 3 - .../WindowsRuntime/MapToDictionaryAdapter.cs | 9 +- .../MapViewToReadOnlyCollectionAdapter.cs | 2 - .../WindowsRuntime/PropertyValue.cs | 1 - .../VectorToCollectionAdapter.cs | 3 - .../WindowsRuntime/VectorToListAdapter.cs | 1 - .../VectorViewToReadOnlyCollectionAdapter.cs | 2 - .../WindowsRuntime/WindowsRuntimeMarshal.cs | 36 ++- .../WindowsRuntime/WindowsRuntimeMetadata.cs | 1 - .../Runtime/Loader/AssemblyLoadContext.cs | 1 - .../src/System/Runtime/MemoryFailPoint.cs | 2 - .../Serialization/FormatterConverter.cs | 18 -- .../Serialization/FormatterServices.cs | 2 - .../Serialization/SerializationInfo.cs | 8 - src/mscorlib/src/System/RuntimeHandles.cs | 6 +- src/mscorlib/src/System/SharedStatics.cs | 1 - src/mscorlib/src/System/String.Comparison.cs | 66 +---- .../src/System/String.Manipulation.cs | 125 +-------- src/mscorlib/src/System/String.Searching.cs | 31 --- src/mscorlib/src/System/String.cs | 36 +-- src/mscorlib/src/System/StubHelpers.cs | 3 - .../src/System/Text/Normalization.Windows.cs | 1 - .../src/System/Threading/EventWaitHandle.cs | 4 - .../System/Threading/ManualResetEventSlim.cs | 3 - src/mscorlib/src/System/Threading/Monitor.cs | 3 - src/mscorlib/src/System/Threading/Mutex.cs | 3 - .../src/System/Threading/Overlapped.cs | 3 - .../src/System/Threading/Semaphore.cs | 1 - .../src/System/Threading/SemaphoreSlim.cs | 3 +- .../Threading/SynchronizationContext.cs | 2 - .../Threading/Tasks/AsyncCausalityTracer.cs | 1 - .../Tasks/ConcurrentExclusiveSchedulerPair.cs | 24 +- .../System/Threading/Tasks/FutureFactory.cs | 47 +--- .../Threading/Tasks/ProducerConsumerQueues.cs | 11 +- .../src/System/Threading/Tasks/Task.cs | 72 ++--- .../Threading/Tasks/TaskCompletionSource.cs | 1 - .../Threading/Tasks/TaskContinuation.cs | 23 +- .../Threading/Tasks/TaskExceptionHolder.cs | 11 +- .../src/System/Threading/Tasks/TaskFactory.cs | 50 +--- .../System/Threading/Tasks/TaskScheduler.cs | 3 +- .../src/System/Threading/Tasks/TaskToApm.cs | 13 +- .../Tasks/ThreadPoolTaskScheduler.cs | 1 - .../src/System/Threading/Tasks/future.cs | 1 - src/mscorlib/src/System/Threading/Thread.cs | 12 - .../src/System/Threading/ThreadLocal.cs | 1 - .../src/System/Threading/ThreadPool.cs | 5 - src/mscorlib/src/System/Threading/Timer.cs | 7 - .../src/System/Threading/WaitHandle.cs | 7 - src/mscorlib/src/System/ThrowHelper.cs | 2 - .../src/System/TimeZoneInfo.AdjustmentRule.cs | 3 - .../src/System/TimeZoneInfo.TransitionTime.cs | 5 - src/mscorlib/src/System/TimeZoneInfo.Unix.cs | 3 - src/mscorlib/src/System/TimeZoneInfo.cs | 11 - src/mscorlib/src/System/Tuple.cs | 1 - src/mscorlib/src/System/Type.CoreCLR.cs | 6 - src/mscorlib/src/System/TypeLoadException.cs | 1 - src/mscorlib/src/System/TypeNameParser.cs | 6 +- src/mscorlib/src/System/TypedReference.cs | 2 - src/mscorlib/src/System/UIntPtr.cs | 4 - src/mscorlib/src/System/Variant.cs | 1 - src/mscorlib/src/System/WeakReference.cs | 3 - src/mscorlib/src/System/WeakReferenceOfT.cs | 3 - 320 files changed, 496 insertions(+), 3003 deletions(-) diff --git a/src/mscorlib/shared/System/Boolean.cs b/src/mscorlib/shared/System/Boolean.cs index a6ffb6de83f7..70edd94e3b6d 100644 --- a/src/mscorlib/shared/System/Boolean.cs +++ b/src/mscorlib/shared/System/Boolean.cs @@ -12,7 +12,6 @@ ** ===========================================================*/ -using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Versioning; diff --git a/src/mscorlib/shared/System/Byte.cs b/src/mscorlib/shared/System/Byte.cs index a0f8ff8c29a5..e087bd4a43ee 100644 --- a/src/mscorlib/shared/System/Byte.cs +++ b/src/mscorlib/shared/System/Byte.cs @@ -185,28 +185,24 @@ private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFor [Pure] public override String ToString() { - Contract.Ensures(Contract.Result() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo); } [Pure] public String ToString(String format) { - Contract.Ensures(Contract.Result() != null); return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo); } [Pure] public String ToString(IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } [Pure] public String ToString(String format, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider)); } diff --git a/src/mscorlib/shared/System/Char.cs b/src/mscorlib/shared/System/Char.cs index bce271406781..1152369869fc 100644 --- a/src/mscorlib/shared/System/Char.cs +++ b/src/mscorlib/shared/System/Char.cs @@ -154,14 +154,12 @@ public int CompareTo(Char value) [Pure] public override String ToString() { - Contract.Ensures(Contract.Result() != null); return Char.ToString(m_value); } [Pure] public String ToString(IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Char.ToString(m_value); } @@ -182,7 +180,6 @@ public static char Parse(String s) { throw new ArgumentNullException(nameof(s)); } - Contract.EndContractBlock(); if (s.Length != 1) { @@ -405,7 +402,6 @@ public static char ToUpper(char c, CultureInfo culture) { if (culture == null) throw new ArgumentNullException(nameof(culture)); - Contract.EndContractBlock(); return culture.TextInfo.ToUpper(c); } @@ -438,7 +434,6 @@ public static char ToLower(char c, CultureInfo culture) { if (culture == null) throw new ArgumentNullException(nameof(culture)); - Contract.EndContractBlock(); return culture.TextInfo.ToLower(c); } @@ -562,7 +557,6 @@ public static bool IsControl(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index)); } - Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { @@ -580,7 +574,6 @@ public static bool IsDigit(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index)); } - Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { @@ -597,7 +590,6 @@ public static bool IsLetter(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index)); } - Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { @@ -619,7 +611,6 @@ public static bool IsLetterOrDigit(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index)); } - Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { @@ -636,7 +627,6 @@ public static bool IsLower(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index)); } - Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { @@ -687,7 +677,6 @@ public static bool IsNumber(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index)); } - Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { @@ -716,7 +705,6 @@ public static bool IsPunctuation(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index)); } - Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { @@ -766,7 +754,6 @@ public static bool IsSeparator(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index)); } - Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { @@ -792,7 +779,6 @@ public static bool IsSurrogate(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index)); } - Contract.EndContractBlock(); return (IsSurrogate(s[index])); } @@ -830,7 +816,6 @@ public static bool IsSymbol(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index)); } - Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { @@ -848,7 +833,6 @@ public static bool IsUpper(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index)); } - Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { @@ -870,7 +854,6 @@ public static bool IsWhiteSpace(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index)); } - Contract.EndContractBlock(); if (IsLatin1(s[index])) { @@ -897,7 +880,6 @@ public static UnicodeCategory GetUnicodeCategory(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index)); } - Contract.EndContractBlock(); if (IsLatin1(s[index])) { return (GetLatin1UnicodeCategory(s[index])); @@ -918,7 +900,6 @@ public static double GetNumericValue(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index)); } - Contract.EndContractBlock(); return CharUnicodeInfo.GetNumericValue(s, index); } @@ -943,7 +924,6 @@ public static bool IsHighSurrogate(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index)); } - Contract.EndContractBlock(); return (IsHighSurrogate(s[index])); } @@ -967,7 +947,6 @@ public static bool IsLowSurrogate(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index)); } - Contract.EndContractBlock(); return (IsLowSurrogate(s[index])); } @@ -985,7 +964,6 @@ public static bool IsSurrogatePair(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index)); } - Contract.EndContractBlock(); if (index + 1 < s.Length) { return (IsSurrogatePair(s[index], s[index + 1])); @@ -1024,7 +1002,6 @@ public static String ConvertFromUtf32(int utf32) { throw new ArgumentOutOfRangeException(nameof(utf32), SR.ArgumentOutOfRange_InvalidUTF32); } - Contract.EndContractBlock(); if (utf32 < UNICODE_PLANE01_START) { @@ -1059,7 +1036,6 @@ public static int ConvertToUtf32(char highSurrogate, char lowSurrogate) { throw new ArgumentOutOfRangeException(nameof(lowSurrogate), SR.ArgumentOutOfRange_InvalidLowSurrogate); } - Contract.EndContractBlock(); return (((highSurrogate - CharUnicodeInfo.HIGH_SURROGATE_START) * 0x400) + (lowSurrogate - CharUnicodeInfo.LOW_SURROGATE_START) + UNICODE_PLANE01_START); } @@ -1082,7 +1058,6 @@ public static int ConvertToUtf32(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } - Contract.EndContractBlock(); // Check if the character at index is a high surrogate. int temp1 = (int)s[index] - CharUnicodeInfo.HIGH_SURROGATE_START; if (temp1 >= 0 && temp1 <= 0x7ff) diff --git a/src/mscorlib/shared/System/Collections/Generic/ICollection.cs b/src/mscorlib/shared/System/Collections/Generic/ICollection.cs index 52852aa1fbec..78ee5cb1f55f 100644 --- a/src/mscorlib/shared/System/Collections/Generic/ICollection.cs +++ b/src/mscorlib/shared/System/Collections/Generic/ICollection.cs @@ -4,7 +4,6 @@ using System; using System.Runtime.CompilerServices; -using System.Diagnostics.Contracts; namespace System.Collections.Generic { diff --git a/src/mscorlib/shared/System/Collections/Generic/IDictionary.cs b/src/mscorlib/shared/System/Collections/Generic/IDictionary.cs index a73a2f55bd31..05677da3b2b7 100644 --- a/src/mscorlib/shared/System/Collections/Generic/IDictionary.cs +++ b/src/mscorlib/shared/System/Collections/Generic/IDictionary.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics.Contracts; namespace System.Collections.Generic { diff --git a/src/mscorlib/shared/System/Collections/Generic/IEnumerable.cs b/src/mscorlib/shared/System/Collections/Generic/IEnumerable.cs index 84264d5cf07c..ddb798e8a6ad 100644 --- a/src/mscorlib/shared/System/Collections/Generic/IEnumerable.cs +++ b/src/mscorlib/shared/System/Collections/Generic/IEnumerable.cs @@ -6,7 +6,6 @@ using System.Collections; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; -using System.Diagnostics.Contracts; namespace System.Collections.Generic { diff --git a/src/mscorlib/shared/System/Collections/Generic/IList.cs b/src/mscorlib/shared/System/Collections/Generic/IList.cs index 43d6659da9c1..2abc7b9142a0 100644 --- a/src/mscorlib/shared/System/Collections/Generic/IList.cs +++ b/src/mscorlib/shared/System/Collections/Generic/IList.cs @@ -5,7 +5,6 @@ using System; using System.Collections; using System.Runtime.CompilerServices; -using System.Diagnostics.Contracts; namespace System.Collections.Generic { diff --git a/src/mscorlib/shared/System/Collections/Generic/IReadOnlyCollection.cs b/src/mscorlib/shared/System/Collections/Generic/IReadOnlyCollection.cs index 09ee89f03573..9eea39de2233 100644 --- a/src/mscorlib/shared/System/Collections/Generic/IReadOnlyCollection.cs +++ b/src/mscorlib/shared/System/Collections/Generic/IReadOnlyCollection.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; namespace System.Collections.Generic diff --git a/src/mscorlib/shared/System/Collections/Generic/IReadOnlyDictionary.cs b/src/mscorlib/shared/System/Collections/Generic/IReadOnlyDictionary.cs index 169e2958bb44..300b9966112b 100644 --- a/src/mscorlib/shared/System/Collections/Generic/IReadOnlyDictionary.cs +++ b/src/mscorlib/shared/System/Collections/Generic/IReadOnlyDictionary.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics.Contracts; namespace System.Collections.Generic { diff --git a/src/mscorlib/shared/System/Collections/Generic/IReadOnlyList.cs b/src/mscorlib/shared/System/Collections/Generic/IReadOnlyList.cs index 00b5be65ff14..7193805b068e 100644 --- a/src/mscorlib/shared/System/Collections/Generic/IReadOnlyList.cs +++ b/src/mscorlib/shared/System/Collections/Generic/IReadOnlyList.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; namespace System.Collections.Generic diff --git a/src/mscorlib/shared/System/Collections/Generic/List.cs b/src/mscorlib/shared/System/Collections/Generic/List.cs index f548f8d1b195..56bbea895eb8 100644 --- a/src/mscorlib/shared/System/Collections/Generic/List.cs +++ b/src/mscorlib/shared/System/Collections/Generic/List.cs @@ -4,7 +4,6 @@ using System.Collections.ObjectModel; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; namespace System.Collections.Generic @@ -24,7 +23,6 @@ public class List : IList, System.Collections.IList, IReadOnlyList private const int DefaultCapacity = 4; private T[] _items; // Do not rename (binary serialization) - [ContractPublicPropertyName("Count")] private int _size; // Do not rename (binary serialization) private int _version; // Do not rename (binary serialization) [NonSerialized] @@ -49,7 +47,6 @@ public List(int capacity) { if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); if (capacity == 0) _items = s_emptyArray; @@ -65,7 +62,6 @@ public List(IEnumerable collection) { if (collection == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); - Contract.EndContractBlock(); ICollection c = collection as ICollection; if (c != null) @@ -98,7 +94,6 @@ public int Capacity { get { - Contract.Ensures(Contract.Result() >= 0); return _items.Length; } set @@ -107,7 +102,6 @@ public int Capacity { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity); } - Contract.EndContractBlock(); if (value != _items.Length) { @@ -133,7 +127,6 @@ public int Count { get { - Contract.Ensures(Contract.Result() >= 0); return _size; } } @@ -183,7 +176,6 @@ public T this[int index] { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } - Contract.EndContractBlock(); return _items[index]; } @@ -193,7 +185,6 @@ public T this[int index] { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } - Contract.EndContractBlock(); _items[index] = value; _version++; } @@ -280,14 +271,11 @@ int System.Collections.IList.Add(Object item) // public void AddRange(IEnumerable collection) { - Contract.Ensures(Count >= Contract.OldValue(Count)); - InsertRange(_size, collection); } public ReadOnlyCollection AsReadOnly() { - Contract.Ensures(Contract.Result>() != null); return new ReadOnlyCollection(this); } @@ -319,21 +307,17 @@ public int BinarySearch(int index, int count, T item, IComparer comparer) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); if (_size - index < count) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); - Contract.Ensures(Contract.Result() <= index + count); - Contract.EndContractBlock(); return Array.BinarySearch(_items, index, count, item, comparer); } public int BinarySearch(T item) { - Contract.Ensures(Contract.Result() <= Count); return BinarySearch(0, Count, item, null); } public int BinarySearch(T item, IComparer comparer) { - Contract.Ensures(Contract.Result() <= Count); return BinarySearch(0, Count, item, comparer); } @@ -391,7 +375,6 @@ public List ConvertAll(Converter converter) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter); } - Contract.EndContractBlock(); List list = new List(_size); for (int i = 0; i < _size; i++) @@ -417,7 +400,6 @@ void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } - Contract.EndContractBlock(); try { @@ -440,7 +422,6 @@ public void CopyTo(int index, T[] array, int arrayIndex, int count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); } - Contract.EndContractBlock(); // Delegate rest of error checking to Array.Copy. Array.Copy(_items, index, array, arrayIndex, count); @@ -481,7 +462,6 @@ public T Find(Predicate match) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - Contract.EndContractBlock(); for (int i = 0; i < _size; i++) { @@ -499,7 +479,6 @@ public List FindAll(Predicate match) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - Contract.EndContractBlock(); List list = new List(); for (int i = 0; i < _size; i++) @@ -514,15 +493,11 @@ public List FindAll(Predicate match) public int FindIndex(Predicate match) { - Contract.Ensures(Contract.Result() >= -1); - Contract.Ensures(Contract.Result() < Count); return FindIndex(0, _size, match); } public int FindIndex(int startIndex, Predicate match) { - Contract.Ensures(Contract.Result() >= -1); - Contract.Ensures(Contract.Result() < startIndex + Count); return FindIndex(startIndex, _size - startIndex, match); } @@ -542,9 +517,6 @@ public int FindIndex(int startIndex, int count, Predicate match) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - Contract.Ensures(Contract.Result() >= -1); - Contract.Ensures(Contract.Result() < startIndex + count); - Contract.EndContractBlock(); int endIndex = startIndex + count; for (int i = startIndex; i < endIndex; i++) @@ -560,7 +532,6 @@ public T FindLast(Predicate match) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - Contract.EndContractBlock(); for (int i = _size - 1; i >= 0; i--) { @@ -574,15 +545,11 @@ public T FindLast(Predicate match) public int FindLastIndex(Predicate match) { - Contract.Ensures(Contract.Result() >= -1); - Contract.Ensures(Contract.Result() < Count); return FindLastIndex(_size - 1, _size, match); } public int FindLastIndex(int startIndex, Predicate match) { - Contract.Ensures(Contract.Result() >= -1); - Contract.Ensures(Contract.Result() <= startIndex); return FindLastIndex(startIndex, startIndex + 1, match); } @@ -592,9 +559,6 @@ public int FindLastIndex(int startIndex, int count, Predicate match) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - Contract.Ensures(Contract.Result() >= -1); - Contract.Ensures(Contract.Result() <= startIndex); - Contract.EndContractBlock(); if (_size == 0) { @@ -636,7 +600,6 @@ public void ForEach(Action action) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action); } - Contract.EndContractBlock(); int version = _version; @@ -689,8 +652,6 @@ public List GetRange(int index, int count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); } - Contract.Ensures(Contract.Result>() != null); - Contract.EndContractBlock(); List list = new List(count); Array.Copy(_items, index, list._items, 0, count); @@ -709,8 +670,6 @@ public List GetRange(int index, int count) // public int IndexOf(T item) { - Contract.Ensures(Contract.Result() >= -1); - Contract.Ensures(Contract.Result() < Count); return Array.IndexOf(_items, item, 0, _size); } @@ -736,9 +695,6 @@ public int IndexOf(T item, int index) { if (index > _size) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); - Contract.Ensures(Contract.Result() >= -1); - Contract.Ensures(Contract.Result() < Count); - Contract.EndContractBlock(); return Array.IndexOf(_items, item, index, _size - index); } @@ -758,9 +714,6 @@ public int IndexOf(T item, int index, int count) if (count < 0 || index > _size - count) ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); - Contract.Ensures(Contract.Result() >= -1); - Contract.Ensures(Contract.Result() < Count); - Contract.EndContractBlock(); return Array.IndexOf(_items, item, index, count); } @@ -776,7 +729,6 @@ public void Insert(int index, T item) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert); } - Contract.EndContractBlock(); if (_size == _items.Length) EnsureCapacity(_size + 1); if (index < _size) { @@ -817,7 +769,6 @@ public void InsertRange(int index, IEnumerable collection) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } - Contract.EndContractBlock(); ICollection c = collection as ICollection; if (c != null) @@ -875,8 +826,6 @@ public void InsertRange(int index, IEnumerable collection) // public int LastIndexOf(T item) { - Contract.Ensures(Contract.Result() >= -1); - Contract.Ensures(Contract.Result() < Count); if (_size == 0) { // Special case for empty list return -1; @@ -900,9 +849,6 @@ public int LastIndexOf(T item, int index) { if (index >= _size) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); - Contract.Ensures(Contract.Result() >= -1); - Contract.Ensures(((Count == 0) && (Contract.Result() == -1)) || ((Count > 0) && (Contract.Result() <= index))); - Contract.EndContractBlock(); return LastIndexOf(item, index, index + 1); } @@ -926,9 +872,6 @@ public int LastIndexOf(T item, int index, int count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } - Contract.Ensures(Contract.Result() >= -1); - Contract.Ensures(((Count == 0) && (Contract.Result() == -1)) || ((Count > 0) && (Contract.Result() <= index))); - Contract.EndContractBlock(); if (_size == 0) { // Special case for empty list @@ -978,9 +921,6 @@ public int RemoveAll(Predicate match) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - Contract.Ensures(Contract.Result() >= 0); - Contract.Ensures(Contract.Result() <= Contract.OldValue(Count)); - Contract.EndContractBlock(); int freeIndex = 0; // the first free slot in items array @@ -1020,7 +960,6 @@ public void RemoveAt(int index) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } - Contract.EndContractBlock(); _size--; if (index < _size) { @@ -1048,7 +987,6 @@ public void RemoveRange(int index, int count) if (_size - index < count) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); - Contract.EndContractBlock(); if (count > 0) { @@ -1092,7 +1030,6 @@ public void Reverse(int index, int count) if (_size - index < count) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); - Contract.EndContractBlock(); if (count > 1) { @@ -1137,7 +1074,6 @@ public void Sort(int index, int count, IComparer comparer) if (_size - index < count) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); - Contract.EndContractBlock(); if (count > 1) { @@ -1152,7 +1088,6 @@ public void Sort(Comparison comparison) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); } - Contract.EndContractBlock(); if (_size > 1) { @@ -1165,9 +1100,6 @@ public void Sort(Comparison comparison) // This requires copying the List, which is an O(n) operation. public T[] ToArray() { - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(Contract.Result().Length == Count); - if (_size == 0) { return s_emptyArray; @@ -1202,7 +1134,6 @@ public bool TrueForAll(Predicate match) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - Contract.EndContractBlock(); for (int i = 0; i < _size; i++) { diff --git a/src/mscorlib/shared/System/Collections/ICollection.cs b/src/mscorlib/shared/System/Collections/ICollection.cs index 8fd6a96b484c..f0149020d24f 100644 --- a/src/mscorlib/shared/System/Collections/ICollection.cs +++ b/src/mscorlib/shared/System/Collections/ICollection.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics.Contracts; namespace System.Collections { diff --git a/src/mscorlib/shared/System/Collections/IDictionary.cs b/src/mscorlib/shared/System/Collections/IDictionary.cs index 8bc7fcf125d3..b934c2399cf2 100644 --- a/src/mscorlib/shared/System/Collections/IDictionary.cs +++ b/src/mscorlib/shared/System/Collections/IDictionary.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics.Contracts; namespace System.Collections { diff --git a/src/mscorlib/shared/System/Collections/IEnumerable.cs b/src/mscorlib/shared/System/Collections/IEnumerable.cs index 91aec6242388..e5edeff266d2 100644 --- a/src/mscorlib/shared/System/Collections/IEnumerable.cs +++ b/src/mscorlib/shared/System/Collections/IEnumerable.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; namespace System.Collections @@ -12,7 +11,6 @@ public interface IEnumerable { // Returns an IEnumerator for this enumerable Object. The enumerator provides // a simple way to access all the contents of a collection. - [Pure] IEnumerator GetEnumerator(); } } diff --git a/src/mscorlib/shared/System/Collections/IList.cs b/src/mscorlib/shared/System/Collections/IList.cs index bb2e221cc116..0110eca1f5eb 100644 --- a/src/mscorlib/shared/System/Collections/IList.cs +++ b/src/mscorlib/shared/System/Collections/IList.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics.Contracts; namespace System.Collections { diff --git a/src/mscorlib/shared/System/Collections/ListDictionaryInternal.cs b/src/mscorlib/shared/System/Collections/ListDictionaryInternal.cs index 681e51a329b2..28593d3c824a 100644 --- a/src/mscorlib/shared/System/Collections/ListDictionaryInternal.cs +++ b/src/mscorlib/shared/System/Collections/ListDictionaryInternal.cs @@ -12,7 +12,6 @@ ** ===========================================================*/ -using System.Diagnostics.Contracts; namespace System.Collections { @@ -46,7 +45,6 @@ public Object this[Object key] { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } - Contract.EndContractBlock(); DictionaryNode node = head; while (node != null) @@ -65,7 +63,6 @@ public Object this[Object key] { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } - Contract.EndContractBlock(); version++; @@ -167,7 +164,6 @@ public void Add(Object key, Object value) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } - Contract.EndContractBlock(); version++; @@ -215,7 +211,6 @@ public bool Contains(Object key) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } - Contract.EndContractBlock(); for (DictionaryNode node = head; node != null; node = node.next) { if (node.key.Equals(key)) @@ -239,7 +234,6 @@ public void CopyTo(Array array, int index) if (array.Length - index < this.Count) throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index)); - Contract.EndContractBlock(); for (DictionaryNode node = head; node != null; node = node.next) { @@ -264,7 +258,6 @@ public void Remove(Object key) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } - Contract.EndContractBlock(); version++; DictionaryNode last = null; DictionaryNode node; @@ -403,7 +396,6 @@ void ICollection.CopyTo(Array array, int index) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); if (array.Length - index < list.Count) throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index)); for (DictionaryNode node = list.head; node != null; node = node.next) diff --git a/src/mscorlib/shared/System/Convert.cs b/src/mscorlib/shared/System/Convert.cs index b16eb7bf2270..4a60164f9412 100644 --- a/src/mscorlib/shared/System/Convert.cs +++ b/src/mscorlib/shared/System/Convert.cs @@ -11,7 +11,6 @@ using System.Runtime.Versioning; using System.Security; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System { @@ -158,7 +157,6 @@ private static bool DoAsserts() // the object does not implement IConvertible), the result is TypeCode.Object. // Otherwise, the result is the type code of the object, as determined by // the object's implementation of IConvertible. - [Pure] public static TypeCode GetTypeCode(object value) { if (value == null) return TypeCode.Empty; @@ -172,7 +170,6 @@ public static TypeCode GetTypeCode(object value) // Returns true if the given object is a database null. This operation // corresponds to "value.GetTypeCode() == TypeCode.DBNull". - [Pure] public static bool IsDBNull(object value) { if (value == System.DBNull.Value) return true; @@ -263,7 +260,6 @@ internal static Object DefaultToType(IConvertible value, Type targetType, IForma { throw new ArgumentNullException(nameof(targetType)); } - Contract.EndContractBlock(); if (ReferenceEquals(value.GetType(), targetType)) { @@ -324,7 +320,6 @@ public static Object ChangeType(Object value, Type conversionType, IFormatProvid { throw new ArgumentNullException(nameof(conversionType)); } - Contract.EndContractBlock(); if (value == null) { @@ -541,7 +536,6 @@ public static char ToChar(char value) public static char ToChar(sbyte value) { if (value < 0) ThrowCharOverflowException(); - Contract.EndContractBlock(); return (char)value; } @@ -553,7 +547,6 @@ public static char ToChar(byte value) public static char ToChar(short value) { if (value < 0) ThrowCharOverflowException(); - Contract.EndContractBlock(); return (char)value; } @@ -566,7 +559,6 @@ public static char ToChar(ushort value) public static char ToChar(int value) { if (value < 0 || value > Char.MaxValue) ThrowCharOverflowException(); - Contract.EndContractBlock(); return (char)value; } @@ -574,14 +566,12 @@ public static char ToChar(int value) public static char ToChar(uint value) { if (value > Char.MaxValue) ThrowCharOverflowException(); - Contract.EndContractBlock(); return (char)value; } public static char ToChar(long value) { if (value < 0 || value > Char.MaxValue) ThrowCharOverflowException(); - Contract.EndContractBlock(); return (char)value; } @@ -589,7 +579,6 @@ public static char ToChar(long value) public static char ToChar(ulong value) { if (value > Char.MaxValue) ThrowCharOverflowException(); - Contract.EndContractBlock(); return (char)value; } @@ -606,7 +595,6 @@ public static char ToChar(String value, IFormatProvider provider) { if (value == null) throw new ArgumentNullException(nameof(value)); - Contract.EndContractBlock(); if (value.Length != 1) throw new FormatException(SR.Format_NeedSingleChar); @@ -674,7 +662,6 @@ public static sbyte ToSByte(sbyte value) public static sbyte ToSByte(char value) { if (value > SByte.MaxValue) ThrowSByteOverflowException(); - Contract.EndContractBlock(); return (sbyte)value; } @@ -682,7 +669,6 @@ public static sbyte ToSByte(char value) public static sbyte ToSByte(byte value) { if (value > SByte.MaxValue) ThrowSByteOverflowException(); - Contract.EndContractBlock(); return (sbyte)value; } @@ -690,7 +676,6 @@ public static sbyte ToSByte(byte value) public static sbyte ToSByte(short value) { if (value < SByte.MinValue || value > SByte.MaxValue) ThrowSByteOverflowException(); - Contract.EndContractBlock(); return (sbyte)value; } @@ -698,7 +683,6 @@ public static sbyte ToSByte(short value) public static sbyte ToSByte(ushort value) { if (value > SByte.MaxValue) ThrowSByteOverflowException(); - Contract.EndContractBlock(); return (sbyte)value; } @@ -706,7 +690,6 @@ public static sbyte ToSByte(ushort value) public static sbyte ToSByte(int value) { if (value < SByte.MinValue || value > SByte.MaxValue) ThrowSByteOverflowException(); - Contract.EndContractBlock(); return (sbyte)value; } @@ -714,7 +697,6 @@ public static sbyte ToSByte(int value) public static sbyte ToSByte(uint value) { if (value > SByte.MaxValue) ThrowSByteOverflowException(); - Contract.EndContractBlock(); return (sbyte)value; } @@ -722,7 +704,6 @@ public static sbyte ToSByte(uint value) public static sbyte ToSByte(long value) { if (value < SByte.MinValue || value > SByte.MaxValue) ThrowSByteOverflowException(); - Contract.EndContractBlock(); return (sbyte)value; } @@ -730,7 +711,6 @@ public static sbyte ToSByte(long value) public static sbyte ToSByte(ulong value) { if (value > (ulong)SByte.MaxValue) ThrowSByteOverflowException(); - Contract.EndContractBlock(); return (sbyte)value; } @@ -800,7 +780,6 @@ public static byte ToByte(byte value) public static byte ToByte(char value) { if (value > Byte.MaxValue) ThrowByteOverflowException(); - Contract.EndContractBlock(); return (byte)value; } @@ -808,14 +787,12 @@ public static byte ToByte(char value) public static byte ToByte(sbyte value) { if (value < Byte.MinValue) ThrowByteOverflowException(); - Contract.EndContractBlock(); return (byte)value; } public static byte ToByte(short value) { if (value < Byte.MinValue || value > Byte.MaxValue) ThrowByteOverflowException(); - Contract.EndContractBlock(); return (byte)value; } @@ -823,14 +800,12 @@ public static byte ToByte(short value) public static byte ToByte(ushort value) { if (value > Byte.MaxValue) ThrowByteOverflowException(); - Contract.EndContractBlock(); return (byte)value; } public static byte ToByte(int value) { if (value < Byte.MinValue || value > Byte.MaxValue) ThrowByteOverflowException(); - Contract.EndContractBlock(); return (byte)value; } @@ -838,14 +813,12 @@ public static byte ToByte(int value) public static byte ToByte(uint value) { if (value > Byte.MaxValue) ThrowByteOverflowException(); - Contract.EndContractBlock(); return (byte)value; } public static byte ToByte(long value) { if (value < Byte.MinValue || value > Byte.MaxValue) ThrowByteOverflowException(); - Contract.EndContractBlock(); return (byte)value; } @@ -853,7 +826,6 @@ public static byte ToByte(long value) public static byte ToByte(ulong value) { if (value > Byte.MaxValue) ThrowByteOverflowException(); - Contract.EndContractBlock(); return (byte)value; } @@ -915,7 +887,6 @@ public static short ToInt16(bool value) public static short ToInt16(char value) { if (value > Int16.MaxValue) ThrowInt16OverflowException(); - Contract.EndContractBlock(); return (short)value; } @@ -934,14 +905,12 @@ public static short ToInt16(byte value) public static short ToInt16(ushort value) { if (value > Int16.MaxValue) ThrowInt16OverflowException(); - Contract.EndContractBlock(); return (short)value; } public static short ToInt16(int value) { if (value < Int16.MinValue || value > Int16.MaxValue) ThrowInt16OverflowException(); - Contract.EndContractBlock(); return (short)value; } @@ -949,7 +918,6 @@ public static short ToInt16(int value) public static short ToInt16(uint value) { if (value > Int16.MaxValue) ThrowInt16OverflowException(); - Contract.EndContractBlock(); return (short)value; } @@ -961,7 +929,6 @@ public static short ToInt16(short value) public static short ToInt16(long value) { if (value < Int16.MinValue || value > Int16.MaxValue) ThrowInt16OverflowException(); - Contract.EndContractBlock(); return (short)value; } @@ -969,7 +936,6 @@ public static short ToInt16(long value) public static short ToInt16(ulong value) { if (value > (ulong)Int16.MaxValue) ThrowInt16OverflowException(); - Contract.EndContractBlock(); return (short)value; } @@ -1042,7 +1008,6 @@ public static ushort ToUInt16(char value) public static ushort ToUInt16(sbyte value) { if (value < 0) ThrowUInt16OverflowException(); - Contract.EndContractBlock(); return (ushort)value; } @@ -1056,7 +1021,6 @@ public static ushort ToUInt16(byte value) public static ushort ToUInt16(short value) { if (value < 0) ThrowUInt16OverflowException(); - Contract.EndContractBlock(); return (ushort)value; } @@ -1064,7 +1028,6 @@ public static ushort ToUInt16(short value) public static ushort ToUInt16(int value) { if (value < 0 || value > UInt16.MaxValue) ThrowUInt16OverflowException(); - Contract.EndContractBlock(); return (ushort)value; } @@ -1078,7 +1041,6 @@ public static ushort ToUInt16(ushort value) public static ushort ToUInt16(uint value) { if (value > UInt16.MaxValue) ThrowUInt16OverflowException(); - Contract.EndContractBlock(); return (ushort)value; } @@ -1087,7 +1049,6 @@ public static ushort ToUInt16(uint value) public static ushort ToUInt16(long value) { if (value < 0 || value > UInt16.MaxValue) ThrowUInt16OverflowException(); - Contract.EndContractBlock(); return (ushort)value; } @@ -1095,7 +1056,6 @@ public static ushort ToUInt16(long value) public static ushort ToUInt16(ulong value) { if (value > UInt16.MaxValue) ThrowUInt16OverflowException(); - Contract.EndContractBlock(); return (ushort)value; } @@ -1191,7 +1151,6 @@ public static int ToInt32(ushort value) public static int ToInt32(uint value) { if (value > Int32.MaxValue) ThrowInt32OverflowException(); - Contract.EndContractBlock(); return (int)value; } @@ -1203,7 +1162,6 @@ public static int ToInt32(int value) public static int ToInt32(long value) { if (value < Int32.MinValue || value > Int32.MaxValue) ThrowInt32OverflowException(); - Contract.EndContractBlock(); return (int)value; } @@ -1211,7 +1169,6 @@ public static int ToInt32(long value) public static int ToInt32(ulong value) { if (value > Int32.MaxValue) ThrowInt32OverflowException(); - Contract.EndContractBlock(); return (int)value; } @@ -1304,7 +1261,6 @@ public static uint ToUInt32(char value) public static uint ToUInt32(sbyte value) { if (value < 0) ThrowUInt32OverflowException(); - Contract.EndContractBlock(); return (uint)value; } @@ -1318,7 +1274,6 @@ public static uint ToUInt32(byte value) public static uint ToUInt32(short value) { if (value < 0) ThrowUInt32OverflowException(); - Contract.EndContractBlock(); return (uint)value; } @@ -1332,7 +1287,6 @@ public static uint ToUInt32(ushort value) public static uint ToUInt32(int value) { if (value < 0) ThrowUInt32OverflowException(); - Contract.EndContractBlock(); return (uint)value; } @@ -1346,7 +1300,6 @@ public static uint ToUInt32(uint value) public static uint ToUInt32(long value) { if (value < 0 || value > UInt32.MaxValue) ThrowUInt32OverflowException(); - Contract.EndContractBlock(); return (uint)value; } @@ -1354,7 +1307,6 @@ public static uint ToUInt32(long value) public static uint ToUInt32(ulong value) { if (value > UInt32.MaxValue) ThrowUInt32OverflowException(); - Contract.EndContractBlock(); return (uint)value; } @@ -1468,7 +1420,6 @@ public static long ToInt64(uint value) public static long ToInt64(ulong value) { if (value > Int64.MaxValue) ThrowInt64OverflowException(); - Contract.EndContractBlock(); return (long)value; } @@ -1546,7 +1497,6 @@ public static ulong ToUInt64(char value) public static ulong ToUInt64(sbyte value) { if (value < 0) ThrowUInt64OverflowException(); - Contract.EndContractBlock(); return (ulong)value; } @@ -1560,7 +1510,6 @@ public static ulong ToUInt64(byte value) public static ulong ToUInt64(short value) { if (value < 0) ThrowUInt64OverflowException(); - Contract.EndContractBlock(); return (ulong)value; } @@ -1574,7 +1523,6 @@ public static ulong ToUInt64(ushort value) public static ulong ToUInt64(int value) { if (value < 0) ThrowUInt64OverflowException(); - Contract.EndContractBlock(); return (ulong)value; } @@ -1588,7 +1536,6 @@ public static ulong ToUInt64(uint value) public static ulong ToUInt64(long value) { if (value < 0) ThrowUInt64OverflowException(); - Contract.EndContractBlock(); return (ulong)value; } @@ -2075,189 +2022,159 @@ public static string ToString(Object value, IFormatProvider provider) public static string ToString(bool value) { - Contract.Ensures(Contract.Result() != null); return value.ToString(); } public static string ToString(bool value, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return value.ToString(); } public static string ToString(char value) { - Contract.Ensures(Contract.Result() != null); return Char.ToString(value); } public static string ToString(char value, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return value.ToString(); } [CLSCompliant(false)] public static string ToString(sbyte value) { - Contract.Ensures(Contract.Result() != null); return value.ToString(CultureInfo.CurrentCulture); } [CLSCompliant(false)] public static string ToString(sbyte value, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return value.ToString(provider); } public static string ToString(byte value) { - Contract.Ensures(Contract.Result() != null); return value.ToString(CultureInfo.CurrentCulture); } public static string ToString(byte value, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return value.ToString(provider); } public static string ToString(short value) { - Contract.Ensures(Contract.Result() != null); return value.ToString(CultureInfo.CurrentCulture); } public static string ToString(short value, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return value.ToString(provider); } [CLSCompliant(false)] public static string ToString(ushort value) { - Contract.Ensures(Contract.Result() != null); return value.ToString(CultureInfo.CurrentCulture); } [CLSCompliant(false)] public static string ToString(ushort value, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return value.ToString(provider); } public static string ToString(int value) { - Contract.Ensures(Contract.Result() != null); return value.ToString(CultureInfo.CurrentCulture); } public static string ToString(int value, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return value.ToString(provider); } [CLSCompliant(false)] public static string ToString(uint value) { - Contract.Ensures(Contract.Result() != null); return value.ToString(CultureInfo.CurrentCulture); } [CLSCompliant(false)] public static string ToString(uint value, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return value.ToString(provider); } public static string ToString(long value) { - Contract.Ensures(Contract.Result() != null); return value.ToString(CultureInfo.CurrentCulture); } public static string ToString(long value, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return value.ToString(provider); } [CLSCompliant(false)] public static string ToString(ulong value) { - Contract.Ensures(Contract.Result() != null); return value.ToString(CultureInfo.CurrentCulture); } [CLSCompliant(false)] public static string ToString(ulong value, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return value.ToString(provider); } public static string ToString(float value) { - Contract.Ensures(Contract.Result() != null); return value.ToString(CultureInfo.CurrentCulture); } public static string ToString(float value, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return value.ToString(provider); } public static string ToString(double value) { - Contract.Ensures(Contract.Result() != null); return value.ToString(CultureInfo.CurrentCulture); } public static string ToString(double value, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return value.ToString(provider); } public static string ToString(decimal value) { - Contract.Ensures(Contract.Result() != null); return value.ToString(CultureInfo.CurrentCulture); } public static string ToString(Decimal value, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return value.ToString(provider); } public static string ToString(DateTime value) { - Contract.Ensures(Contract.Result() != null); return value.ToString(); } public static string ToString(DateTime value, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return value.ToString(provider); } public static String ToString(String value) { - Contract.Ensures(Contract.Result() == value); // We were always skipping the null check here. return value; } public static String ToString(String value, IFormatProvider provider) { - Contract.Ensures(Contract.Result() == value); // We were always skipping the null check here. return value; // avoid the null check } @@ -2275,7 +2192,6 @@ public static byte ToByte(String value, int fromBase) { throw new ArgumentException(SR.Arg_InvalidBase); } - Contract.EndContractBlock(); if (value == null) { @@ -2299,7 +2215,6 @@ public static sbyte ToSByte(String value, int fromBase) { throw new ArgumentException(SR.Arg_InvalidBase); } - Contract.EndContractBlock(); if (value == null) { @@ -2325,7 +2240,6 @@ public static short ToInt16(String value, int fromBase) { throw new ArgumentException(SR.Arg_InvalidBase); } - Contract.EndContractBlock(); if (value == null) { @@ -2352,7 +2266,6 @@ public static ushort ToUInt16(String value, int fromBase) { throw new ArgumentException(SR.Arg_InvalidBase); } - Contract.EndContractBlock(); if (value == null) { @@ -2375,7 +2288,6 @@ public static int ToInt32(String value, int fromBase) { throw new ArgumentException(SR.Arg_InvalidBase); } - Contract.EndContractBlock(); return value != null ? ParseNumbers.StringToInt(value.AsReadOnlySpan(), fromBase, ParseNumbers.IsTight) : 0; @@ -2392,7 +2304,6 @@ public static uint ToUInt32(String value, int fromBase) { throw new ArgumentException(SR.Arg_InvalidBase); } - Contract.EndContractBlock(); return value != null ? (uint)ParseNumbers.StringToInt(value.AsReadOnlySpan(), fromBase, ParseNumbers.TreatAsUnsigned | ParseNumbers.IsTight) : 0; @@ -2408,7 +2319,6 @@ public static long ToInt64(String value, int fromBase) { throw new ArgumentException(SR.Arg_InvalidBase); } - Contract.EndContractBlock(); return value != null ? ParseNumbers.StringToLong(value.AsReadOnlySpan(), fromBase, ParseNumbers.IsTight) : 0; @@ -2425,7 +2335,6 @@ public static ulong ToUInt64(String value, int fromBase) { throw new ArgumentException(SR.Arg_InvalidBase); } - Contract.EndContractBlock(); return value != null ? (ulong)ParseNumbers.StringToLong(value.AsReadOnlySpan(), fromBase, ParseNumbers.TreatAsUnsigned | ParseNumbers.IsTight) : 0; @@ -2438,7 +2347,6 @@ public static String ToString(byte value, int toBase) { throw new ArgumentException(SR.Arg_InvalidBase); } - Contract.EndContractBlock(); return ParseNumbers.IntToString((int)value, toBase, -1, ' ', ParseNumbers.PrintAsI1); } @@ -2449,7 +2357,6 @@ public static String ToString(short value, int toBase) { throw new ArgumentException(SR.Arg_InvalidBase); } - Contract.EndContractBlock(); return ParseNumbers.IntToString((int)value, toBase, -1, ' ', ParseNumbers.PrintAsI2); } @@ -2460,7 +2367,6 @@ public static String ToString(int value, int toBase) { throw new ArgumentException(SR.Arg_InvalidBase); } - Contract.EndContractBlock(); return ParseNumbers.IntToString(value, toBase, -1, ' ', 0); } @@ -2471,7 +2377,6 @@ public static String ToString(long value, int toBase) { throw new ArgumentException(SR.Arg_InvalidBase); } - Contract.EndContractBlock(); return ParseNumbers.LongToString(value, toBase, -1, ' ', 0); } @@ -2481,8 +2386,6 @@ public static String ToBase64String(byte[] inArray) { throw new ArgumentNullException(nameof(inArray)); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return ToBase64String(inArray, 0, inArray.Length, Base64FormattingOptions.None); } @@ -2492,8 +2395,6 @@ public static String ToBase64String(byte[] inArray, Base64FormattingOptions opti { throw new ArgumentNullException(nameof(inArray)); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return ToBase64String(inArray, 0, inArray.Length, options); } @@ -2513,8 +2414,6 @@ public static unsafe String ToBase64String(byte[] inArray, int offset, int lengt throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_GenericPositive); if (options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks) throw new ArgumentException(string.Format(SR.Arg_EnumIllegalVal, (int)options)); - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); int inArrayLength; int stringLength; @@ -2544,10 +2443,6 @@ public static unsafe String ToBase64String(byte[] inArray, int offset, int lengt public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut) { - Contract.Ensures(Contract.Result() >= 0); - Contract.Ensures(Contract.Result() <= outArray.Length); - Contract.EndContractBlock(); - return ToBase64CharArray(inArray, offsetIn, length, outArray, offsetOut, Base64FormattingOptions.None); } @@ -2569,9 +2464,6 @@ public static unsafe int ToBase64CharArray(byte[] inArray, int offsetIn, int len { throw new ArgumentException(string.Format(SR.Arg_EnumIllegalVal, (int)options)); } - Contract.Ensures(Contract.Result() >= 0); - Contract.Ensures(Contract.Result() <= outArray.Length); - Contract.EndContractBlock(); int retVal; @@ -2710,7 +2602,6 @@ public static Byte[] FromBase64String(String s) if (s == null) throw new ArgumentNullException(nameof(s)); - Contract.EndContractBlock(); unsafe { @@ -2743,7 +2634,6 @@ public static Byte[] FromBase64CharArray(Char[] inArray, Int32 offset, Int32 len if (offset > inArray.Length - length) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_OffsetLength); - Contract.EndContractBlock(); if (inArray.Length == 0) { diff --git a/src/mscorlib/shared/System/CurrentSystemTimeZone.cs b/src/mscorlib/shared/System/CurrentSystemTimeZone.cs index 3f17d6f3717e..bab6a92bf553 100644 --- a/src/mscorlib/shared/System/CurrentSystemTimeZone.cs +++ b/src/mscorlib/shared/System/CurrentSystemTimeZone.cs @@ -18,7 +18,6 @@ ============================================================*/ using System; -using System.Diagnostics.Contracts; using System.Text; using System.Collections; using System.Globalization; diff --git a/src/mscorlib/shared/System/DateTime.cs b/src/mscorlib/shared/System/DateTime.cs index e72654a8d63b..99a444d5e9b5 100644 --- a/src/mscorlib/shared/System/DateTime.cs +++ b/src/mscorlib/shared/System/DateTime.cs @@ -4,7 +4,6 @@ using System; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Threading; using System.Globalization; using System.Runtime; @@ -18,7 +17,6 @@ namespace System { - // This value type represents a date and time. Every DateTime // object has a private field (Ticks) of type Int64 that stores the // date and time as the number of 100 nanosecond intervals since @@ -147,7 +145,6 @@ public DateTime(long ticks) { if (ticks < MinTicks || ticks > MaxTicks) throw new ArgumentOutOfRangeException(nameof(ticks), SR.ArgumentOutOfRange_DateTimeBadTicks); - Contract.EndContractBlock(); _dateData = (UInt64)ticks; } @@ -166,7 +163,6 @@ public DateTime(long ticks, DateTimeKind kind) { throw new ArgumentException(SR.Argument_InvalidDateTimeKind, nameof(kind)); } - Contract.EndContractBlock(); _dateData = ((UInt64)ticks | ((UInt64)kind << KindShift)); } @@ -177,7 +173,6 @@ internal DateTime(long ticks, DateTimeKind kind, Boolean isAmbiguousDst) throw new ArgumentOutOfRangeException(nameof(ticks), SR.ArgumentOutOfRange_DateTimeBadTicks); } Debug.Assert(kind == DateTimeKind.Local, "Internal Constructor is for local times only"); - Contract.EndContractBlock(); _dateData = ((UInt64)ticks | (isAmbiguousDst ? KindLocalAmbiguousDst : KindLocal)); } @@ -212,7 +207,6 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, { throw new ArgumentException(SR.Argument_InvalidDateTimeKind, nameof(kind)); } - Contract.EndContractBlock(); Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); _dateData = ((UInt64)ticks | ((UInt64)kind << KindShift)); } @@ -224,7 +218,6 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, { if (calendar == null) throw new ArgumentNullException(nameof(calendar)); - Contract.EndContractBlock(); _dateData = (UInt64)calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks; } @@ -237,7 +230,6 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, { throw new ArgumentOutOfRangeException(nameof(millisecond), SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)); } - Contract.EndContractBlock(); Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); ticks += millisecond * TicksPerMillisecond; if (ticks < MinTicks || ticks > MaxTicks) @@ -255,7 +247,6 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, { throw new ArgumentException(SR.Argument_InvalidDateTimeKind, nameof(kind)); } - Contract.EndContractBlock(); Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); ticks += millisecond * TicksPerMillisecond; if (ticks < MinTicks || ticks > MaxTicks) @@ -274,7 +265,6 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, { throw new ArgumentOutOfRangeException(nameof(millisecond), SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)); } - Contract.EndContractBlock(); Int64 ticks = calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks; ticks += millisecond * TicksPerMillisecond; if (ticks < MinTicks || ticks > MaxTicks) @@ -294,7 +284,6 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, { throw new ArgumentException(SR.Argument_InvalidDateTimeKind, nameof(kind)); } - Contract.EndContractBlock(); Int64 ticks = calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks; ticks += millisecond * TicksPerMillisecond; if (ticks < MinTicks || ticks > MaxTicks) @@ -306,7 +295,6 @@ private DateTime(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); Boolean foundTicks = false; Boolean foundDateData = false; @@ -452,7 +440,6 @@ public DateTime AddMinutes(double value) public DateTime AddMonths(int months) { if (months < -120000 || months > 120000) throw new ArgumentOutOfRangeException(nameof(months), SR.ArgumentOutOfRange_DateTimeBadMonths); - Contract.EndContractBlock(); GetDatePart(out int y, out int m, out int d); int i = m - 1 + months; if (i >= 0) @@ -515,7 +502,6 @@ public DateTime AddYears(int value) // parameter name out of the two for the exception. throw new ArgumentOutOfRangeException("years", SR.ArgumentOutOfRange_DateTimeBadYears); } - Contract.EndContractBlock(); return AddMonths(value * 12); } @@ -589,7 +575,6 @@ private static long TimeToTicks(int hour, int minute, int second) public static int DaysInMonth(int year, int month) { if (month < 1 || month > 12) throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month); - Contract.EndContractBlock(); // IsLeapYear checks the year argument int[] days = IsLeapYear(year) ? s_daysToMonth366 : s_daysToMonth365; return days[month] - days[month - 1]; @@ -725,7 +710,6 @@ public static DateTime FromFileTimeUtc(long fileTime) { throw new ArgumentOutOfRangeException(nameof(fileTime), SR.ArgumentOutOfRange_FileTimeInvalid); } - Contract.EndContractBlock(); // This is the ticks in Universal time for this fileTime. long universalTicks = fileTime + FileTimeOffset; @@ -745,7 +729,6 @@ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext contex { throw new ArgumentNullException(nameof(info)); } - Contract.EndContractBlock(); // Serialize both the old and the new format info.AddValue(TicksField, InternalTicks); @@ -909,8 +892,6 @@ public int Day { get { - Contract.Ensures(Contract.Result() >= 1); - Contract.Ensures(Contract.Result() <= 31); return GetDatePart(DatePartDay); } } @@ -924,8 +905,6 @@ public DayOfWeek DayOfWeek { get { - Contract.Ensures(Contract.Result() >= DayOfWeek.Sunday); - Contract.Ensures(Contract.Result() <= DayOfWeek.Saturday); return (DayOfWeek)((InternalTicks / TicksPerDay + 1) % 7); } } @@ -937,8 +916,6 @@ public int DayOfYear { get { - Contract.Ensures(Contract.Result() >= 1); - Contract.Ensures(Contract.Result() <= 366); // leap year return GetDatePart(DatePartDayOfYear); } } @@ -958,8 +935,6 @@ public int Hour { get { - Contract.Ensures(Contract.Result() >= 0); - Contract.Ensures(Contract.Result() < 24); return (int)((InternalTicks / TicksPerHour) % 24); } } @@ -969,7 +944,6 @@ internal Boolean IsAmbiguousDaylightSavingTime() return (InternalKind == KindLocalAmbiguousDst); } - [Pure] public DateTimeKind Kind { get @@ -993,8 +967,6 @@ public int Millisecond { get { - Contract.Ensures(Contract.Result() >= 0); - Contract.Ensures(Contract.Result() < 1000); return (int)((InternalTicks / TicksPerMillisecond) % 1000); } } @@ -1006,8 +978,6 @@ public int Minute { get { - Contract.Ensures(Contract.Result() >= 0); - Contract.Ensures(Contract.Result() < 60); return (int)((InternalTicks / TicksPerMinute) % 60); } } @@ -1019,7 +989,6 @@ public int Month { get { - Contract.Ensures(Contract.Result() >= 1); return GetDatePart(DatePartMonth); } } @@ -1030,8 +999,6 @@ public static DateTime Now { get { - Contract.Ensures(Contract.Result().Kind == DateTimeKind.Local); - DateTime utc = UtcNow; Boolean isAmbiguousLocalDst = false; Int64 offset = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utc, out isAmbiguousLocalDst).Ticks; @@ -1055,8 +1022,6 @@ public int Second { get { - Contract.Ensures(Contract.Result() >= 0); - Contract.Ensures(Contract.Result() < 60); return (int)((InternalTicks / TicksPerSecond) % 60); } } @@ -1103,7 +1068,6 @@ public int Year { get { - Contract.Ensures(Contract.Result() >= 1 && Contract.Result() <= 9999); return GetDatePart(DatePartYear); } } @@ -1117,7 +1081,6 @@ public static bool IsLeapYear(int year) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_Year); } - Contract.EndContractBlock(); return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } @@ -1265,49 +1228,41 @@ internal DateTime ToLocalTime(bool throwOnOverflow) public String ToLongDateString() { - Contract.Ensures(Contract.Result() != null); return DateTimeFormat.Format(this, "D", DateTimeFormatInfo.CurrentInfo); } public String ToLongTimeString() { - Contract.Ensures(Contract.Result() != null); return DateTimeFormat.Format(this, "T", DateTimeFormatInfo.CurrentInfo); } public String ToShortDateString() { - Contract.Ensures(Contract.Result() != null); return DateTimeFormat.Format(this, "d", DateTimeFormatInfo.CurrentInfo); } public String ToShortTimeString() { - Contract.Ensures(Contract.Result() != null); return DateTimeFormat.Format(this, "t", DateTimeFormatInfo.CurrentInfo); } public override String ToString() { - Contract.Ensures(Contract.Result() != null); return DateTimeFormat.Format(this, null, DateTimeFormatInfo.CurrentInfo); } public String ToString(String format) { - Contract.Ensures(Contract.Result() != null); return DateTimeFormat.Format(this, format, DateTimeFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return DateTimeFormat.Format(this, null, DateTimeFormatInfo.GetInstance(provider)); } public String ToString(String format, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return DateTimeFormat.Format(this, format, DateTimeFormatInfo.GetInstance(provider)); } @@ -1402,7 +1357,6 @@ public static Boolean TryParseExact(String s, String[] formats, IFormatProvider // time strings for the current instance of DateTime. public String[] GetDateTimeFormats() { - Contract.Ensures(Contract.Result() != null); return (GetDateTimeFormats(CultureInfo.CurrentCulture)); } @@ -1411,7 +1365,6 @@ public String[] GetDateTimeFormats() // time strings for the current instance of DateTime. public String[] GetDateTimeFormats(IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return (DateTimeFormat.GetAllDateTimes(this, DateTimeFormatInfo.GetInstance(provider))); } @@ -1421,7 +1374,6 @@ public String[] GetDateTimeFormats(IFormatProvider provider) // time strings for the current instance of DateTime. public String[] GetDateTimeFormats(char format) { - Contract.Ensures(Contract.Result() != null); return (GetDateTimeFormats(format, CultureInfo.CurrentCulture)); } @@ -1430,7 +1382,6 @@ public String[] GetDateTimeFormats(char format) // time strings for the current instance of DateTime. public String[] GetDateTimeFormats(char format, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return (DateTimeFormat.GetAllDateTimes(this, format, DateTimeFormatInfo.GetInstance(provider))); } diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/ActivityTracker.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/ActivityTracker.cs index bb52a9bb9453..cb0526c1ccc6 100644 --- a/src/mscorlib/shared/System/Diagnostics/Tracing/ActivityTracker.cs +++ b/src/mscorlib/shared/System/Diagnostics/Tracing/ActivityTracker.cs @@ -5,12 +5,6 @@ using System; using System.Diagnostics; using System.Threading; -#if !ES_BUILD_AGAINST_DOTNET_V35 -using Contract = System.Diagnostics.Contracts.Contract; -#else -using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; -#endif - #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else @@ -43,7 +37,6 @@ namespace System.Diagnostics.Tracing /// internal class ActivityTracker { - /// /// Called on work item begins. The activity name = providerName + activityName without 'Start' suffix. /// It updates CurrentActivityId to track. diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/EventDescriptor.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/EventDescriptor.cs index 8fb471a99f7c..6dce32ce9946 100644 --- a/src/mscorlib/shared/System/Diagnostics/Tracing/EventDescriptor.cs +++ b/src/mscorlib/shared/System/Diagnostics/Tracing/EventDescriptor.cs @@ -9,12 +9,6 @@ using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; #endif -#if !ES_BUILD_AGAINST_DOTNET_V35 -using Contract = System.Diagnostics.Contracts.Contract; -#else -using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; -#endif - #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/EventProvider.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/EventProvider.cs index a74125a35aa3..d9f1747131f0 100644 --- a/src/mscorlib/shared/System/Diagnostics/Tracing/EventProvider.cs +++ b/src/mscorlib/shared/System/Diagnostics/Tracing/EventProvider.cs @@ -14,12 +14,6 @@ using System.Threading; using System; -#if !ES_BUILD_AGAINST_DOTNET_V35 -using Contract = System.Diagnostics.Contracts.Contract; -#else -using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; -#endif - #if ES_BUILD_AGAINST_DOTNET_V35 using Microsoft.Internal; // for Tuple (can't define alias for open generic types so we "use" the whole namespace) #endif @@ -634,7 +628,6 @@ public bool IsEnabled(byte level, long keywords) if ((level <= m_level) || (m_level == 0)) { - // // Check if Keyword is enabled // diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/EventSource.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/EventSource.cs index 4e436e7baf25..fb1521398478 100644 --- a/src/mscorlib/shared/System/Diagnostics/Tracing/EventSource.cs +++ b/src/mscorlib/shared/System/Diagnostics/Tracing/EventSource.cs @@ -197,12 +197,6 @@ using Microsoft.Reflection; -#if !ES_BUILD_AGAINST_DOTNET_V35 -using Contract = System.Diagnostics.Contracts.Contract; -#else -using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; -#endif - #if CORECLR || ES_BUILD_PN using Internal.Runtime.Augments; #endif @@ -250,7 +244,6 @@ namespace System.Diagnostics.Tracing /// public partial class EventSource : IDisposable { - #if FEATURE_EVENTSOURCE_XPLAT private static readonly EventListener persistent_Xplat_Listener = XplatEventLogger.InitializePersistentListener(); #endif //FEATURE_EVENTSOURCE_XPLAT @@ -405,7 +398,6 @@ public static Guid GetGuid(Type eventSourceType) { if (eventSourceType == null) throw new ArgumentNullException(nameof(eventSourceType)); - Contract.EndContractBlock(); EventSourceAttribute attrib = (EventSourceAttribute)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute)); string name = eventSourceType.Name; @@ -473,7 +465,6 @@ public static string GenerateManifest(Type eventSourceType, string assemblyPathT { if (eventSourceType == null) throw new ArgumentNullException(nameof(eventSourceType)); - Contract.EndContractBlock(); byte[] manifestBytes = EventSource.CreateManifestAndDescriptors(eventSourceType, assemblyPathToIncludeInManifest, null, flags); return (manifestBytes == null) ? null : Encoding.UTF8.GetString(manifestBytes, 0, manifestBytes.Length); @@ -1259,7 +1250,6 @@ protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, Guid* rel #if FEATURE_MANAGED_ETW if (m_eventData[eventId].EnabledForETW) { - #if FEATURE_ACTIVITYSAMPLING // this code should be kept in sync with WriteEventVarargs(). SessionMask etwSessions = SessionMask.All; @@ -1623,7 +1613,6 @@ private static string GetName(Type eventSourceType, EventManifestOptions flags) { if (eventSourceType == null) throw new ArgumentNullException(nameof(eventSourceType)); - Contract.EndContractBlock(); EventSourceAttribute attrib = (EventSourceAttribute)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute), flags); if (attrib != null && attrib.Name != null) @@ -3599,7 +3588,6 @@ private static byte[] CreateManifestAndDescriptors(Type eventSourceType, string string.Compare(startEventMetadata.Name, 0, taskName, 0, taskName.Length) == 0 && string.Compare(startEventMetadata.Name, taskName.Length, s_ActivityStartSuffix, 0, Math.Max(startEventMetadata.Name.Length - taskName.Length, s_ActivityStartSuffix.Length)) == 0) { - // Make the stop event match the start event eventAttribute.Task = (EventTask)startEventMetadata.Descriptor.Task; noTask = false; @@ -4455,7 +4443,6 @@ public void EnableEvents(EventSource eventSource, EventLevel level, EventKeyword { throw new ArgumentNullException(nameof(eventSource)); } - Contract.EndContractBlock(); eventSource.SendCommand(this, 0, 0, EventCommand.Update, true, level, matchAnyKeyword, arguments); } @@ -4470,7 +4457,6 @@ public void DisableEvents(EventSource eventSource) { throw new ArgumentNullException(nameof(eventSource)); } - Contract.EndContractBlock(); eventSource.SendCommand(this, 0, 0, EventCommand.Update, false, EventLevel.LogAlways, EventKeywords.None, null); } @@ -4946,7 +4932,6 @@ public ReadOnlyCollection PayloadNames // do the lazy init if you know it is contract based (EventID >= 0) if (EventId >= 0 && m_payloadNames == null) { - var names = new List(); foreach (var parameter in m_eventSource.m_eventData[EventId].Parameters) { @@ -6461,7 +6446,6 @@ public void ManifestError(string msg, bool runtimeCritical = false) private string CreateManifestString() { - #if FEATURE_MANAGED_ETW_CHANNELS // Write out the channels if (channelTab != null) @@ -6529,7 +6513,6 @@ private string CreateManifestString() // Write out the tasks if (taskTab != null) { - sb.Append(" ").AppendLine(); var sortedTasks = new List(taskTab.Keys); sortedTasks.Sort(); diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/StubEnvironment.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/StubEnvironment.cs index b365841d5f6e..5797d4d09c5e 100644 --- a/src/mscorlib/shared/System/Diagnostics/Tracing/StubEnvironment.cs +++ b/src/mscorlib/shared/System/Diagnostics/Tracing/StubEnvironment.cs @@ -52,29 +52,6 @@ public static string GetRuntimeResourceString(string key, params object[] args) #if ES_BUILD_AGAINST_DOTNET_V35 -namespace Microsoft.Diagnostics.Contracts.Internal -{ - internal class Contract - { - public static void Assert(bool invariant) - { - Assert(invariant, string.Empty); - } - public static void Assert(bool invariant, string message) - { - if (!invariant) - { - if (System.Diagnostics.Debugger.IsAttached) - System.Diagnostics.Debugger.Break(); - throw new Exception("Assertion failed: " + message); - } - } - public static void EndContractBlock() - { } - } -} - - namespace Microsoft.Internal { using System.Text; diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs index 5967ad6ab58c..abe9ece13c65 100644 --- a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs +++ b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs @@ -6,12 +6,6 @@ using System.Collections; using System.Diagnostics; -#if !ES_BUILD_AGAINST_DOTNET_V35 -using Contract = System.Diagnostics.Contracts.Contract; -#else -using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; -#endif - #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs index acc3eeb233d2..ef2ec4715cdd 100644 --- a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs +++ b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs @@ -4,12 +4,6 @@ using System; -#if !ES_BUILD_AGAINST_DOTNET_V35 -using Contract = System.Diagnostics.Contracts.Contract; -#else -using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; -#endif - #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else @@ -36,7 +30,6 @@ public EventSourceActivity(EventSource eventSource) { if (eventSource == null) throw new ArgumentNullException(nameof(eventSource)); - Contract.EndContractBlock(); this.eventSource = eventSource; } diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs index aeee3ad9e31f..d74494bc85ff 100644 --- a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs +++ b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs @@ -2,12 +2,6 @@ using System.Runtime.InteropServices; using System.Diagnostics; -#if !ES_BUILD_AGAINST_DOTNET_V35 -using Contract = System.Diagnostics.Contracts.Contract; -#else -using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; -#endif - namespace System.Diagnostics.Tracing { /// diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs index 901a0ed1a212..61cb92ffade3 100644 --- a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs +++ b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs @@ -7,12 +7,6 @@ using System.Reflection; using System.Diagnostics; -#if !ES_BUILD_AGAINST_DOTNET_V35 -using Contract = System.Diagnostics.Contracts.Contract; -#else -using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; -#endif - #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs index a1218d1a7f93..8d12b64a0897 100644 --- a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs +++ b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs @@ -29,11 +29,9 @@ using System.Collections.ObjectModel; #if !ES_BUILD_AGAINST_DOTNET_V35 -using Contract = System.Diagnostics.Contracts.Contract; using System.Collections.Generic; using System.Text; #else -using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; using System.Collections.Generic; using System.Text; #endif @@ -102,7 +100,6 @@ public EventSource( { throw new ArgumentNullException(nameof(eventSourceName)); } - Contract.EndContractBlock(); } /// @@ -117,7 +114,6 @@ public unsafe void Write(string eventName) throw new ArgumentNullException(nameof(eventName)); } - Contract.EndContractBlock(); if (!this.IsEnabled()) { @@ -144,7 +140,6 @@ public unsafe void Write(string eventName, EventSourceOptions options) throw new ArgumentNullException(nameof(eventName)); } - Contract.EndContractBlock(); if (!this.IsEnabled()) { diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs index c2239671bbf2..d024b218d88b 100644 --- a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs +++ b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs @@ -6,12 +6,6 @@ using System.Collections.Generic; using Interlocked = System.Threading.Interlocked; -#if !ES_BUILD_AGAINST_DOTNET_V35 -using Contract = System.Diagnostics.Contracts.Contract; -#else -using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; -#endif - #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else @@ -97,7 +91,6 @@ internal TraceLoggingEventTypes( throw new ArgumentNullException(nameof(name)); } - Contract.EndContractBlock(); this.typeInfos = MakeArray(paramInfos); this.name = name; @@ -135,7 +128,6 @@ private TraceLoggingEventTypes( throw new ArgumentNullException(nameof(defaultName)); } - Contract.EndContractBlock(); this.typeInfos = typeInfos; this.name = defaultName; @@ -215,7 +207,6 @@ private TraceLoggingTypeInfo[] MakeArray(System.Reflection.ParameterInfo[] param throw new ArgumentNullException(nameof(paramInfos)); } - Contract.EndContractBlock(); var recursionCheck = new List(paramInfos.Length); var result = new TraceLoggingTypeInfo[paramInfos.Length]; @@ -234,7 +225,6 @@ private static TraceLoggingTypeInfo[] MakeArray(Type[] types) throw new ArgumentNullException(nameof(types)); } - Contract.EndContractBlock(); var recursionCheck = new List(types.Length); var result = new TraceLoggingTypeInfo[types.Length]; @@ -254,7 +244,6 @@ private static TraceLoggingTypeInfo[] MakeArray( throw new ArgumentNullException(nameof(typeInfos)); } - Contract.EndContractBlock(); return (TraceLoggingTypeInfo[])typeInfos.Clone(); ; } diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingTypeInfo.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingTypeInfo.cs index d68e106b0b4b..81f80c63f797 100644 --- a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingTypeInfo.cs +++ b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingTypeInfo.cs @@ -5,12 +5,6 @@ using System; using System.Collections.Generic; -#if !ES_BUILD_AGAINST_DOTNET_V35 -using Contract = System.Diagnostics.Contracts.Contract; -#else -using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; -#endif - #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else @@ -39,7 +33,6 @@ internal TraceLoggingTypeInfo(Type dataType) throw new ArgumentNullException(nameof(dataType)); } - Contract.EndContractBlock(); this.name = dataType.Name; this.dataType = dataType; @@ -64,7 +57,6 @@ internal TraceLoggingTypeInfo( throw new ArgumentNullException(nameof(name)); } - Contract.EndContractBlock(); Statics.CheckName(name); diff --git a/src/mscorlib/shared/System/Double.cs b/src/mscorlib/shared/System/Double.cs index 7ee52027f317..363c896fa863 100644 --- a/src/mscorlib/shared/System/Double.cs +++ b/src/mscorlib/shared/System/Double.cs @@ -12,7 +12,6 @@ ** ===========================================================*/ -using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -44,7 +43,6 @@ public struct Double : IComparable, IConvertible, IFormattable, IComparableDetermines whether the specified value is finite (zero, subnormal, or normal). - [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsFinite(double d) @@ -54,7 +52,6 @@ public unsafe static bool IsFinite(double d) } /// Determines whether the specified value is infinite. - [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsInfinity(double d) @@ -64,7 +61,6 @@ public unsafe static bool IsInfinity(double d) } /// Determines whether the specified value is NaN. - [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNaN(double d) @@ -74,7 +70,6 @@ public unsafe static bool IsNaN(double d) } /// Determines whether the specified value is negative. - [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNegative(double d) @@ -84,7 +79,6 @@ public unsafe static bool IsNegative(double d) } /// Determines whether the specified value is negative infinity. - [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNegativeInfinity(double d) @@ -93,7 +87,6 @@ public static bool IsNegativeInfinity(double d) } /// Determines whether the specified value is normal. - [Pure] [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called public unsafe static bool IsNormal(double d) @@ -104,7 +97,6 @@ public unsafe static bool IsNormal(double d) } /// Determines whether the specified value is positive infinity. - [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsPositiveInfinity(double d) @@ -113,7 +105,6 @@ public static bool IsPositiveInfinity(double d) } /// Determines whether the specified value is subnormal. - [Pure] [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called public unsafe static bool IsSubnormal(double d) @@ -244,25 +235,21 @@ public unsafe override int GetHashCode() public override String ToString() { - Contract.Ensures(Contract.Result() != null); return Number.FormatDouble(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(String format) { - Contract.Ensures(Contract.Result() != null); return Number.FormatDouble(m_value, format, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatDouble(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatDouble(m_value, format, NumberFormatInfo.GetInstance(provider)); } diff --git a/src/mscorlib/shared/System/Globalization/Calendar.cs b/src/mscorlib/shared/System/Globalization/Calendar.cs index e6ab2477d640..49ad597ceb78 100644 --- a/src/mscorlib/shared/System/Globalization/Calendar.cs +++ b/src/mscorlib/shared/System/Globalization/Calendar.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System.Globalization @@ -151,7 +150,6 @@ public virtual object Clone() public static Calendar ReadOnly(Calendar calendar) { if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); } - Contract.EndContractBlock(); if (calendar.IsReadOnly) { return (calendar); } Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone()); @@ -211,7 +209,6 @@ internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxV String.Format(CultureInfo.InvariantCulture, SR.Format(SR.Argument_ResultCalendarRange, minValue, maxValue))); } - Contract.EndContractBlock(); } internal DateTime Add(DateTime time, double value, int scale) @@ -633,7 +630,6 @@ public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek nameof(firstDayOfWeek), SR.Format(SR.ArgumentOutOfRange_Range, DayOfWeek.Sunday, DayOfWeek.Saturday)); } - Contract.EndContractBlock(); switch (rule) { case CalendarWeekRule.FirstDay: @@ -803,7 +799,6 @@ public virtual int ToFourDigitYear(int year) throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } - Contract.EndContractBlock(); if (year < 100) { return ((TwoDigitYearMax / 100 - (year > TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year); diff --git a/src/mscorlib/shared/System/Globalization/CalendarData.Unix.cs b/src/mscorlib/shared/System/Globalization/CalendarData.Unix.cs index a2ceeb1e67ec..35ee82d3cb58 100644 --- a/src/mscorlib/shared/System/Globalization/CalendarData.Unix.cs +++ b/src/mscorlib/shared/System/Globalization/CalendarData.Unix.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Security; using System.Text; diff --git a/src/mscorlib/shared/System/Globalization/ChineseLunisolarCalendar.cs b/src/mscorlib/shared/System/Globalization/ChineseLunisolarCalendar.cs index e09011a9d82e..d2b52b97be38 100644 --- a/src/mscorlib/shared/System/Globalization/ChineseLunisolarCalendar.cs +++ b/src/mscorlib/shared/System/Globalization/ChineseLunisolarCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Diagnostics.Contracts; namespace System.Globalization { @@ -320,7 +319,6 @@ internal override int GetYearInfo(int lunarYear, int index) CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR)); } - Contract.EndContractBlock(); return s_yinfo[lunarYear - MIN_LUNISOLAR_YEAR, index]; } @@ -345,7 +343,6 @@ internal override int GetGregorianYear(int year, int era) CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR)); } - Contract.EndContractBlock(); return year; } diff --git a/src/mscorlib/shared/System/Globalization/CultureData.Unix.cs b/src/mscorlib/shared/System/Globalization/CultureData.Unix.cs index 4f685de58095..c21d8c3f22af 100644 --- a/src/mscorlib/shared/System/Globalization/CultureData.Unix.cs +++ b/src/mscorlib/shared/System/Globalization/CultureData.Unix.cs @@ -5,7 +5,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Security; using System.Text; diff --git a/src/mscorlib/shared/System/Globalization/DateTimeFormat.cs b/src/mscorlib/shared/System/Globalization/DateTimeFormat.cs index d6afc1b099b4..f129f7313625 100644 --- a/src/mscorlib/shared/System/Globalization/DateTimeFormat.cs +++ b/src/mscorlib/shared/System/Globalization/DateTimeFormat.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Globalization; using System.Text; @@ -970,7 +969,7 @@ internal static String Format(DateTime dateTime, String format, DateTimeFormatIn internal static String Format(DateTime dateTime, String format, DateTimeFormatInfo dtfi, TimeSpan offset) { - Contract.Requires(dtfi != null); + Debug.Assert(dtfi != null); if (format == null || format.Length == 0) { Boolean timeOnlySpecialCase = false; @@ -1130,7 +1129,7 @@ internal static void AppendNumber(StringBuilder builder, long val, int digits) internal static String[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi) { - Contract.Requires(dtfi != null); + Debug.Assert(dtfi != null); String[] allFormats = null; String[] results = null; diff --git a/src/mscorlib/shared/System/Globalization/DateTimeFormatInfo.cs b/src/mscorlib/shared/System/Globalization/DateTimeFormatInfo.cs index 9f8c072c9398..7c4200af7b18 100644 --- a/src/mscorlib/shared/System/Globalization/DateTimeFormatInfo.cs +++ b/src/mscorlib/shared/System/Globalization/DateTimeFormatInfo.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System.Globalization @@ -430,7 +429,6 @@ public static DateTimeFormatInfo InvariantInfo { get { - Contract.Ensures(Contract.Result() != null); if (s_invariantInfo == null) { DateTimeFormatInfo info = new DateTimeFormatInfo(); @@ -449,7 +447,6 @@ public static DateTimeFormatInfo CurrentInfo { get { - Contract.Ensures(Contract.Result() != null); System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CurrentCulture; if (!culture._isInherited) { @@ -531,7 +528,6 @@ public String AMDesignator throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String); } - Contract.EndContractBlock(); ClearTokenHashTable(); amDesignator = value; } @@ -542,8 +538,6 @@ public Calendar Calendar { get { - Contract.Ensures(Contract.Result() != null); - Debug.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null"); return (this.calendar); } @@ -556,7 +550,6 @@ public Calendar Calendar { throw new ArgumentNullException(nameof(value), SR.ArgumentNull_Obj); } - Contract.EndContractBlock(); if (value == calendar) { return; @@ -664,7 +657,6 @@ public int GetEra(String eraName) throw new ArgumentNullException(nameof(eraName), SR.ArgumentNull_String); } - Contract.EndContractBlock(); // The Era Name and Abbreviated Era Name // for Taiwan Calendar on non-Taiwan SKU returns empty string (which @@ -820,7 +812,6 @@ public string DateSeparator { throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String); } - Contract.EndContractBlock(); ClearTokenHashTable(); dateSeparator = value; } @@ -905,7 +896,6 @@ public String FullDateTimePattern throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String); } - Contract.EndContractBlock(); fullDateTimePattern = value; } } @@ -939,7 +929,6 @@ public String LongDatePattern throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String); } - Contract.EndContractBlock(); // Remember the new string this.longDatePattern = value; @@ -980,7 +969,6 @@ public String LongTimePattern throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String); } - Contract.EndContractBlock(); // Remember the new string this.longTimePattern = value; @@ -1019,7 +1007,6 @@ public String MonthDayPattern throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String); } - Contract.EndContractBlock(); this.monthDayPattern = value; } @@ -1047,7 +1034,6 @@ public String PMDesignator throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String); } - Contract.EndContractBlock(); ClearTokenHashTable(); pmDesignator = value; @@ -1089,7 +1075,6 @@ public String ShortDatePattern if (value == null) throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String); - Contract.EndContractBlock(); // Remember the new string this.shortDatePattern = value; @@ -1132,7 +1117,6 @@ public String ShortTimePattern throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String); } - Contract.EndContractBlock(); // Remember the new string this.shortTimePattern = value; @@ -1289,7 +1273,6 @@ public string TimeSeparator throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String); } - Contract.EndContractBlock(); ClearTokenHashTable(); timeSeparator = value; @@ -1331,7 +1314,6 @@ public String YearMonthPattern throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String); } - Contract.EndContractBlock(); // Remember the new string this.yearMonthPattern = value; @@ -1379,7 +1361,6 @@ public String[] AbbreviatedDayNames { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 7), nameof(value)); } - Contract.EndContractBlock(); CheckNullValue(value, value.Length); ClearTokenHashTable(); @@ -1408,7 +1389,6 @@ public String[] ShortestDayNames { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 7), nameof(value)); } - Contract.EndContractBlock(); CheckNullValue(value, value.Length); this.m_superShortDayNames = value; } @@ -1435,7 +1415,6 @@ public String[] DayNames { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 7), nameof(value)); } - Contract.EndContractBlock(); CheckNullValue(value, value.Length); ClearTokenHashTable(); @@ -1464,7 +1443,6 @@ public String[] AbbreviatedMonthNames { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 13), nameof(value)); } - Contract.EndContractBlock(); CheckNullValue(value, value.Length - 1); ClearTokenHashTable(); abbreviatedMonthNames = value; @@ -1492,7 +1470,6 @@ public String[] MonthNames { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 13), nameof(value)); } - Contract.EndContractBlock(); CheckNullValue(value, value.Length - 1); monthNames = value; ClearTokenHashTable(); @@ -1620,7 +1597,6 @@ public String GetAbbreviatedDayName(DayOfWeek dayofweek) nameof(dayofweek), SR.Format(SR.ArgumentOutOfRange_Range, DayOfWeek.Sunday, DayOfWeek.Saturday)); } - Contract.EndContractBlock(); // // Don't call the public property AbbreviatedDayNames here since a clone is needed in that // property, so it will be slower. Instead, use GetAbbreviatedDayOfWeekNames() directly. @@ -1637,7 +1613,6 @@ public string GetShortestDayName(DayOfWeek dayOfWeek) nameof(dayOfWeek), SR.Format(SR.ArgumentOutOfRange_Range, DayOfWeek.Sunday, DayOfWeek.Saturday)); } - Contract.EndContractBlock(); // // Don't call the public property SuperShortDayNames here since a clone is needed in that // property, so it will be slower. Instead, use internalGetSuperShortDayNames() directly. @@ -1686,7 +1661,6 @@ public string[] GetAllDateTimePatterns() public string[] GetAllDateTimePatterns(char format) { - Contract.Ensures(Contract.Result() != null); String[] result = null; switch (format) @@ -1753,7 +1727,6 @@ public String GetDayName(DayOfWeek dayofweek) nameof(dayofweek), SR.Format(SR.ArgumentOutOfRange_Range, DayOfWeek.Sunday, DayOfWeek.Saturday)); } - Contract.EndContractBlock(); // Use the internal one so that we don't clone the array unnecessarily return (internalGetDayOfWeekNames()[(int)dayofweek]); @@ -1769,7 +1742,6 @@ public String GetAbbreviatedMonthName(int month) nameof(month), SR.Format(SR.ArgumentOutOfRange_Range, 1, 13)); } - Contract.EndContractBlock(); // Use the internal one so we don't clone the array unnecessarily return (internalGetAbbreviatedMonthNames()[month - 1]); } @@ -1783,7 +1755,6 @@ public String GetMonthName(int month) nameof(month), SR.Format(SR.ArgumentOutOfRange_Range, 1, 13)); } - Contract.EndContractBlock(); // Use the internal one so we don't clone the array unnecessarily return (internalGetMonthNames()[month - 1]); } @@ -1988,7 +1959,6 @@ public static DateTimeFormatInfo ReadOnly(DateTimeFormatInfo dtfi) throw new ArgumentNullException(nameof(dtfi), SR.ArgumentNull_Obj); } - Contract.EndContractBlock(); if (dtfi.IsReadOnly) { return (dtfi); @@ -2055,7 +2025,6 @@ public void SetAllDateTimePatterns(String[] patterns, char format) throw new ArgumentException(SR.Arg_ArrayZeroError, nameof(patterns)); } - Contract.EndContractBlock(); for (int i = 0; i < patterns.Length; i++) { @@ -2122,7 +2091,6 @@ public String[] AbbreviatedMonthGenitiveNames { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 13), nameof(value)); } - Contract.EndContractBlock(); CheckNullValue(value, value.Length - 1); ClearTokenHashTable(); this.m_genitiveAbbreviatedMonthNames = value; @@ -2149,7 +2117,6 @@ public String[] MonthGenitiveNames { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 13), nameof(value)); } - Contract.EndContractBlock(); CheckNullValue(value, value.Length - 1); genitiveMonthNames = value; ClearTokenHashTable(); @@ -2229,7 +2196,6 @@ internal static void ValidateStyles(DateTimeStyles style, String parameterName) { throw new ArgumentException(SR.Argument_ConflictingDateTimeStyles, parameterName); } - Contract.EndContractBlock(); if (((style & DateTimeStyles.RoundtripKind) != 0) && ((style & (DateTimeStyles.AssumeLocal | DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)) != 0)) { diff --git a/src/mscorlib/shared/System/Globalization/DateTimeFormatInfoScanner.cs b/src/mscorlib/shared/System/Globalization/DateTimeFormatInfoScanner.cs index 15af1b7d843f..c38e7a26b85c 100644 --- a/src/mscorlib/shared/System/Globalization/DateTimeFormatInfoScanner.cs +++ b/src/mscorlib/shared/System/Globalization/DateTimeFormatInfoScanner.cs @@ -24,7 +24,6 @@ namespace System.Globalization { - #if CORECLR using StringStringDictionary = Dictionary; using StringList = List; diff --git a/src/mscorlib/shared/System/Globalization/DateTimeParse.cs b/src/mscorlib/shared/System/Globalization/DateTimeParse.cs index f821a954129c..2825f0107e8a 100644 --- a/src/mscorlib/shared/System/Globalization/DateTimeParse.cs +++ b/src/mscorlib/shared/System/Globalization/DateTimeParse.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Globalization; using System.Text; @@ -4678,7 +4677,6 @@ private static Exception GetDateTimeParseException(ref DateTimeResult result) // COMPlus_LogToConsole=1 // COMPlus_LogLevel=9 // COMPlus_ManagedLogFacility=0x00001000 - [Pure] [Conditional("_LOGGING")] internal static void LexTraceExit(string message, DS dps) { @@ -4688,7 +4686,6 @@ internal static void LexTraceExit(string message, DS dps) BCLDebug.Trace("DATETIME", "[DATETIME] Lex return {0}, DS.{1}", message, dps); #endif // _LOGGING } - [Pure] [Conditional("_LOGGING")] internal static void PTSTraceExit(DS dps, bool passed) { @@ -4698,7 +4695,6 @@ internal static void PTSTraceExit(DS dps, bool passed) BCLDebug.Trace("DATETIME", "[DATETIME] ProcessTerminalState {0} @ DS.{1}", passed ? "passed" : "failed", dps); #endif // _LOGGING } - [Pure] [Conditional("_LOGGING")] internal static void TPTraceExit(string message, DS dps) { @@ -4708,7 +4704,6 @@ internal static void TPTraceExit(string message, DS dps) BCLDebug.Trace("DATETIME", "[DATETIME] TryParse return {0}, DS.{1}", message, dps); #endif // _LOGGING } - [Pure] [Conditional("_LOGGING")] internal static void DTFITrace(DateTimeFormatInfo dtfi) { @@ -4733,7 +4728,6 @@ internal static void DTFITrace(DateTimeFormatInfo dtfi) #endif // _LOGGING } #if _LOGGING - [Pure] // return a string in the form: "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" internal static string Hex(string[] strs) { @@ -4787,7 +4781,6 @@ internal static string Hex(string[] strs) buffer.Append(s); return buffer.ToString(); } - [Pure] // return a string in the form: "Sun" internal static string Hex(string str) { @@ -4803,7 +4796,6 @@ internal static string Hex(string str) buffer.Append("\""); return buffer.ToString(); } - [Pure] // return an unicode escaped string form of char c internal static String Hex(char c) { diff --git a/src/mscorlib/shared/System/Globalization/EastAsianLunisolarCalendar.cs b/src/mscorlib/shared/System/Globalization/EastAsianLunisolarCalendar.cs index 383e0cd17c93..358f4df18256 100644 --- a/src/mscorlib/shared/System/Globalization/EastAsianLunisolarCalendar.cs +++ b/src/mscorlib/shared/System/Globalization/EastAsianLunisolarCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Diagnostics.Contracts; namespace System.Globalization { @@ -62,7 +61,6 @@ public int GetCelestialStem(int sexagenaryYear) nameof(sexagenaryYear), SR.Format(SR.ArgumentOutOfRange_Range, 1, 60)); } - Contract.EndContractBlock(); return ((sexagenaryYear - 1) % 10) + 1; } @@ -79,7 +77,6 @@ public int GetTerrestrialBranch(int sexagenaryYear) nameof(sexagenaryYear), SR.Format(SR.ArgumentOutOfRange_Range, 1, 60)); } - Contract.EndContractBlock(); return ((sexagenaryYear - 1) % 12) + 1; } @@ -168,7 +165,6 @@ internal void CheckTicksRange(long ticks) String.Format(CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, MinSupportedDateTime, MaxSupportedDateTime)); } - Contract.EndContractBlock(); } internal void CheckEraRange(int era) @@ -440,7 +436,6 @@ public override DateTime AddMonths(DateTime time, int months) nameof(months), SR.Format(SR.ArgumentOutOfRange_Range, -120000, 120000)); } - Contract.EndContractBlock(); CheckTicksRange(time.Ticks); @@ -699,7 +694,6 @@ public override int ToFourDigitYear(int year) throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } - Contract.EndContractBlock(); year = base.ToFourDigitYear(year); CheckYearRange(year, CurrentEra); diff --git a/src/mscorlib/shared/System/Globalization/GregorianCalendar.cs b/src/mscorlib/shared/System/Globalization/GregorianCalendar.cs index 65041af15f33..81058ff6646f 100644 --- a/src/mscorlib/shared/System/Globalization/GregorianCalendar.cs +++ b/src/mscorlib/shared/System/Globalization/GregorianCalendar.cs @@ -4,7 +4,6 @@ using System; using System.Globalization; -using System.Diagnostics.Contracts; using System.Threading; namespace System.Globalization @@ -99,7 +98,6 @@ public GregorianCalendar(GregorianCalendarTypes type) SR.Format(SR.ArgumentOutOfRange_Range, GregorianCalendarTypes.Localized, GregorianCalendarTypes.TransliteratedFrench)); } - Contract.EndContractBlock(); this.m_type = type; } @@ -214,7 +212,6 @@ public override DateTime AddMonths(DateTime time, int months) -120000, 120000)); } - Contract.EndContractBlock(); time.GetDatePart(out int y, out int m, out int d); int i = m - 1 + months; if (i >= 0) @@ -396,7 +393,6 @@ public override bool IsLeapDay(int year, int month, int day, int era) throw new ArgumentOutOfRangeException(nameof(month), SR.Format(SR.ArgumentOutOfRange_Range, 1, 12)); } - Contract.EndContractBlock(); if (era != CurrentEra && era != ADEra) { @@ -443,7 +439,6 @@ public override int GetLeapMonth(int year, int era) CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } - Contract.EndContractBlock(); return (0); } @@ -472,7 +467,6 @@ public override bool IsLeapMonth(int year, int month, int era) throw new ArgumentOutOfRangeException(nameof(month), SR.Format(SR.ArgumentOutOfRange_Range, 1, 12)); } - Contract.EndContractBlock(); return (false); } @@ -573,7 +567,6 @@ public override int ToFourDigitYear(int year) throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } - Contract.EndContractBlock(); if (year > MaxYear) { diff --git a/src/mscorlib/shared/System/Globalization/GregorianCalendarHelper.cs b/src/mscorlib/shared/System/Globalization/GregorianCalendarHelper.cs index d694202ed1b7..2842bd3a1687 100644 --- a/src/mscorlib/shared/System/Globalization/GregorianCalendarHelper.cs +++ b/src/mscorlib/shared/System/Globalization/GregorianCalendarHelper.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics.Contracts; using System.Threading; namespace System.Globalization @@ -141,7 +140,6 @@ internal int GetGregorianYear(int year, int era) throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } - Contract.EndContractBlock(); if (era == Calendar.CurrentEra) { @@ -323,7 +321,6 @@ internal void CheckTicksRange(long ticks) m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime)); } - Contract.EndContractBlock(); } // Returns the DateTime resulting from adding the given number of @@ -355,7 +352,6 @@ public DateTime AddMonths(DateTime time, int months) -120000, 120000)); } - Contract.EndContractBlock(); CheckTicksRange(time.Ticks); int y = GetDatePart(time.Ticks, DatePartYear); @@ -427,7 +423,6 @@ public int GetDayOfYear(DateTime time) // Returns the number of days in the month given by the year and // month arguments. // - [Pure] public int GetDaysInMonth(int year, int month, int era) { // @@ -555,7 +550,6 @@ public bool IsLeapDay(int year, int month, int day, int era) 1, GetDaysInMonth(year, month, era))); } - Contract.EndContractBlock(); if (!IsLeapYear(year, era)) { @@ -633,7 +627,6 @@ public int ToFourDigitYear(int year, int twoDigitYearMax) throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedPosNum); } - Contract.EndContractBlock(); if (year < 100) { diff --git a/src/mscorlib/shared/System/Globalization/HebrewCalendar.cs b/src/mscorlib/shared/System/Globalization/HebrewCalendar.cs index 92f4cab4be68..533d3831bffd 100644 --- a/src/mscorlib/shared/System/Globalization/HebrewCalendar.cs +++ b/src/mscorlib/shared/System/Globalization/HebrewCalendar.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Globalization { @@ -1095,7 +1094,6 @@ public override int ToFourDigitYear(int year) throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } - Contract.EndContractBlock(); if (year < 100) { diff --git a/src/mscorlib/shared/System/Globalization/HijriCalendar.cs b/src/mscorlib/shared/System/Globalization/HijriCalendar.cs index 59b354f534c9..675584462053 100644 --- a/src/mscorlib/shared/System/Globalization/HijriCalendar.cs +++ b/src/mscorlib/shared/System/Globalization/HijriCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Diagnostics.Contracts; namespace System.Globalization { @@ -198,7 +197,6 @@ public int HijriAdjustment MinAdvancedHijri, MaxAdvancedHijri)); } - Contract.EndContractBlock(); VerifyWritable(); _hijriAdvance = value; @@ -395,7 +393,6 @@ public override DateTime AddMonths(DateTime time, int months) -120000, 120000)); } - Contract.EndContractBlock(); // Get the date in Hijri calendar. int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); @@ -467,7 +464,6 @@ public override int GetDayOfYear(DateTime time) // Returns the number of days in the month given by the year and // month arguments. // - [Pure] public override int GetDaysInMonth(int year, int month, int era) { CheckYearMonthRange(year, month, era); @@ -653,7 +649,6 @@ public override int ToFourDigitYear(int year) throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } - Contract.EndContractBlock(); if (year < 100) { diff --git a/src/mscorlib/shared/System/Globalization/JapaneseCalendar.cs b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.cs index 0db1e6517a23..50195d7f1c98 100644 --- a/src/mscorlib/shared/System/Globalization/JapaneseCalendar.cs +++ b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.Contracts; namespace System.Globalization { @@ -225,7 +224,6 @@ public override int GetMonthsInYear(int year, int era) } - [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return (helper.GetWeekOfYear(time, rule, firstDayOfWeek)); @@ -300,7 +298,6 @@ public override int ToFourDigitYear(int year) throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedPosNum); } - Contract.EndContractBlock(); if (year > helper.MaxYear) { diff --git a/src/mscorlib/shared/System/Globalization/JapaneseLunisolarCalendar.cs b/src/mscorlib/shared/System/Globalization/JapaneseLunisolarCalendar.cs index a90c4e8f216c..e8a2dcd63783 100644 --- a/src/mscorlib/shared/System/Globalization/JapaneseLunisolarCalendar.cs +++ b/src/mscorlib/shared/System/Globalization/JapaneseLunisolarCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Diagnostics.Contracts; namespace System.Globalization { @@ -211,7 +210,6 @@ internal override int GetYearInfo(int lunarYear, int index) MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR)); } - Contract.EndContractBlock(); return s_yinfo[lunarYear - MIN_LUNISOLAR_YEAR, index]; } diff --git a/src/mscorlib/shared/System/Globalization/JulianCalendar.cs b/src/mscorlib/shared/System/Globalization/JulianCalendar.cs index 8d9429054746..82e4d589d33b 100644 --- a/src/mscorlib/shared/System/Globalization/JulianCalendar.cs +++ b/src/mscorlib/shared/System/Globalization/JulianCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Diagnostics.Contracts; namespace System.Globalization { @@ -221,7 +220,6 @@ public override DateTime AddMonths(DateTime time, int months) -120000, 120000)); } - Contract.EndContractBlock(); int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); @@ -424,7 +422,6 @@ public override int ToFourDigitYear(int year) throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } - Contract.EndContractBlock(); if (year > MaxYear) { diff --git a/src/mscorlib/shared/System/Globalization/KoreanCalendar.cs b/src/mscorlib/shared/System/Globalization/KoreanCalendar.cs index ef7495f07dc8..9168b664e026 100644 --- a/src/mscorlib/shared/System/Globalization/KoreanCalendar.cs +++ b/src/mscorlib/shared/System/Globalization/KoreanCalendar.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.Contracts; namespace System.Globalization { @@ -153,7 +152,6 @@ public override int GetMonthsInYear(int year, int era) } - [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return (helper.GetWeekOfYear(time, rule, firstDayOfWeek)); @@ -257,7 +255,6 @@ public override int ToFourDigitYear(int year) throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } - Contract.EndContractBlock(); return (helper.ToFourDigitYear(year, this.TwoDigitYearMax)); } diff --git a/src/mscorlib/shared/System/Globalization/KoreanLunisolarCalendar.cs b/src/mscorlib/shared/System/Globalization/KoreanLunisolarCalendar.cs index 8364532c9eea..8cdade866c50 100644 --- a/src/mscorlib/shared/System/Globalization/KoreanLunisolarCalendar.cs +++ b/src/mscorlib/shared/System/Globalization/KoreanLunisolarCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Diagnostics.Contracts; namespace System.Globalization { @@ -1256,7 +1255,6 @@ internal override int GetYearInfo(int lunarYear, int index) MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR)); } - Contract.EndContractBlock(); return s_yinfo[lunarYear - MIN_LUNISOLAR_YEAR, index]; } @@ -1278,7 +1276,6 @@ internal override int GetGregorianYear(int year, int era) CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR)); } - Contract.EndContractBlock(); return year; } diff --git a/src/mscorlib/shared/System/Globalization/LocaleData.Unix.cs b/src/mscorlib/shared/System/Globalization/LocaleData.Unix.cs index d4c58d8a3dd5..ccf1078ac636 100644 --- a/src/mscorlib/shared/System/Globalization/LocaleData.Unix.cs +++ b/src/mscorlib/shared/System/Globalization/LocaleData.Unix.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using System.Diagnostics.Contracts; // This file contains the handling of Windows OS specific culture features. diff --git a/src/mscorlib/shared/System/Globalization/NumberFormatInfo.cs b/src/mscorlib/shared/System/Globalization/NumberFormatInfo.cs index d7412bfcf3eb..787e36433e11 100644 --- a/src/mscorlib/shared/System/Globalization/NumberFormatInfo.cs +++ b/src/mscorlib/shared/System/Globalization/NumberFormatInfo.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics.Contracts; using System.Runtime.Serialization; using System.Text; @@ -117,7 +116,6 @@ private static void VerifyDecimalSeparator(String decSep, String propertyName) { throw new ArgumentException(SR.Argument_EmptyDecString); } - Contract.EndContractBlock(); } private static void VerifyGroupSeparator(String groupSep, String propertyName) @@ -127,7 +125,6 @@ private static void VerifyGroupSeparator(String groupSep, String propertyName) throw new ArgumentNullException(propertyName, SR.ArgumentNull_String); } - Contract.EndContractBlock(); } private static void VerifyNativeDigits(string[] nativeDig, string propertyName) @@ -141,7 +138,6 @@ private static void VerifyNativeDigits(string[] nativeDig, string propertyName) { throw new ArgumentException(SR.Argument_InvalidNativeDigitCount, propertyName); } - Contract.EndContractBlock(); for (int i = 0; i < nativeDig.Length; i++) { @@ -205,14 +201,12 @@ internal NumberFormatInfo(CultureData cultureData) } } - [Pure] private void VerifyWritable() { if (isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - Contract.EndContractBlock(); } // Returns a default NumberFormatInfo that will be universally @@ -290,7 +284,6 @@ public int CurrencyDecimalDigits 0, 99)); } - Contract.EndContractBlock(); VerifyWritable(); currencyDecimalDigits = value; } @@ -354,7 +347,6 @@ public int[] CurrencyGroupSizes throw new ArgumentNullException(nameof(CurrencyGroupSizes), SR.ArgumentNull_Obj); } - Contract.EndContractBlock(); VerifyWritable(); Int32[] inputSizes = (Int32[])value.Clone(); @@ -378,7 +370,6 @@ public int[] NumberGroupSizes throw new ArgumentNullException(nameof(NumberGroupSizes), SR.ArgumentNull_Obj); } - Contract.EndContractBlock(); VerifyWritable(); Int32[] inputSizes = (Int32[])value.Clone(); @@ -401,7 +392,6 @@ public int[] PercentGroupSizes throw new ArgumentNullException(nameof(PercentGroupSizes), SR.ArgumentNull_Obj); } - Contract.EndContractBlock(); VerifyWritable(); Int32[] inputSizes = (Int32[])value.Clone(); CheckGroupSize(nameof(PercentGroupSizes), inputSizes); @@ -432,7 +422,6 @@ public String CurrencySymbol throw new ArgumentNullException(nameof(CurrencySymbol), SR.ArgumentNull_String); } - Contract.EndContractBlock(); VerifyWritable(); currencySymbol = value; } @@ -472,7 +461,6 @@ public String NaNSymbol throw new ArgumentNullException(nameof(NaNSymbol), SR.ArgumentNull_String); } - Contract.EndContractBlock(); VerifyWritable(); nanSymbol = value; } @@ -495,7 +483,6 @@ public int CurrencyNegativePattern 0, 15)); } - Contract.EndContractBlock(); VerifyWritable(); currencyNegativePattern = value; } @@ -520,7 +507,6 @@ public int NumberNegativePattern 0, 4)); } - Contract.EndContractBlock(); VerifyWritable(); numberNegativePattern = value; } @@ -545,7 +531,6 @@ public int PercentPositivePattern 0, 3)); } - Contract.EndContractBlock(); VerifyWritable(); percentPositivePattern = value; } @@ -570,7 +555,6 @@ public int PercentNegativePattern 0, 11)); } - Contract.EndContractBlock(); VerifyWritable(); percentNegativePattern = value; } @@ -590,7 +574,6 @@ public String NegativeInfinitySymbol throw new ArgumentNullException(nameof(NegativeInfinitySymbol), SR.ArgumentNull_String); } - Contract.EndContractBlock(); VerifyWritable(); negativeInfinitySymbol = value; } @@ -607,7 +590,6 @@ public String NegativeSign throw new ArgumentNullException(nameof(NegativeSign), SR.ArgumentNull_String); } - Contract.EndContractBlock(); VerifyWritable(); negativeSign = value; } @@ -629,7 +611,6 @@ public int NumberDecimalDigits 0, 99)); } - Contract.EndContractBlock(); VerifyWritable(); numberDecimalDigits = value; } @@ -675,7 +656,6 @@ public int CurrencyPositivePattern 0, 3)); } - Contract.EndContractBlock(); VerifyWritable(); currencyPositivePattern = value; } @@ -695,7 +675,6 @@ public String PositiveInfinitySymbol throw new ArgumentNullException(nameof(PositiveInfinitySymbol), SR.ArgumentNull_String); } - Contract.EndContractBlock(); VerifyWritable(); positiveInfinitySymbol = value; } @@ -712,7 +691,6 @@ public String PositiveSign throw new ArgumentNullException(nameof(PositiveSign), SR.ArgumentNull_String); } - Contract.EndContractBlock(); VerifyWritable(); positiveSign = value; } @@ -734,7 +712,6 @@ public int PercentDecimalDigits 0, 99)); } - Contract.EndContractBlock(); VerifyWritable(); percentDecimalDigits = value; } @@ -778,7 +755,6 @@ public String PercentSymbol throw new ArgumentNullException(nameof(PercentSymbol), SR.ArgumentNull_String); } - Contract.EndContractBlock(); VerifyWritable(); percentSymbol = value; } @@ -795,7 +771,6 @@ public String PerMilleSymbol throw new ArgumentNullException(nameof(PerMilleSymbol), SR.ArgumentNull_String); } - Contract.EndContractBlock(); VerifyWritable(); perMilleSymbol = value; } @@ -834,7 +809,6 @@ public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi) { throw new ArgumentNullException(nameof(nfi)); } - Contract.EndContractBlock(); if (nfi.IsReadOnly) { return (nfi); @@ -858,7 +832,6 @@ internal static void ValidateParseStyleInteger(NumberStyles style) { throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style)); } - Contract.EndContractBlock(); if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number if ((style & ~NumberStyles.HexNumber) != 0) @@ -875,7 +848,6 @@ internal static void ValidateParseStyleFloatingPoint(NumberStyles style) { throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style)); } - Contract.EndContractBlock(); if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number throw new ArgumentException(SR.Arg_HexStyleNotSupported); diff --git a/src/mscorlib/shared/System/Globalization/PersianCalendar.cs b/src/mscorlib/shared/System/Globalization/PersianCalendar.cs index 78a081e1b91d..a80c6ece5b7c 100644 --- a/src/mscorlib/shared/System/Globalization/PersianCalendar.cs +++ b/src/mscorlib/shared/System/Globalization/PersianCalendar.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Globalization { @@ -289,7 +288,6 @@ public override DateTime AddMonths(DateTime time, int months) -120000, 120000)); } - Contract.EndContractBlock(); // Get the date in Persian calendar. int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); @@ -582,7 +580,6 @@ public override int ToFourDigitYear(int year) throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } - Contract.EndContractBlock(); if (year < 100) { diff --git a/src/mscorlib/shared/System/Globalization/SortKey.cs b/src/mscorlib/shared/System/Globalization/SortKey.cs index d65e097cb40d..9b706fdad937 100644 --- a/src/mscorlib/shared/System/Globalization/SortKey.cs +++ b/src/mscorlib/shared/System/Globalization/SortKey.cs @@ -15,7 +15,6 @@ using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Globalization { @@ -114,7 +113,6 @@ public static int Compare(SortKey sortkey1, SortKey sortkey2) { throw new ArgumentNullException((sortkey1 == null ? nameof(sortkey1) : nameof(sortkey2))); } - Contract.EndContractBlock(); byte[] key1Data = sortkey1._keyData; byte[] key2Data = sortkey2._keyData; diff --git a/src/mscorlib/shared/System/Globalization/StringInfo.cs b/src/mscorlib/shared/System/Globalization/StringInfo.cs index 87d1b9f68461..c2fbe5a1d618 100644 --- a/src/mscorlib/shared/System/Globalization/StringInfo.cs +++ b/src/mscorlib/shared/System/Globalization/StringInfo.cs @@ -14,7 +14,6 @@ using System; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System.Globalization @@ -95,7 +94,6 @@ public string String throw new ArgumentNullException(nameof(String), SR.ArgumentNull_String); } - Contract.EndContractBlock(); _str = value; _indexes = null; @@ -280,7 +278,6 @@ public static string GetNextTextElement(string str, int index) { throw new ArgumentNullException(nameof(str)); } - Contract.EndContractBlock(); int len = str.Length; if (index < 0 || index >= len) @@ -311,7 +308,6 @@ public static TextElementEnumerator GetTextElementEnumerator(string str, int ind { throw new ArgumentNullException(nameof(str)); } - Contract.EndContractBlock(); int len = str.Length; if (index < 0 || (index > len)) @@ -340,7 +336,6 @@ public static int[] ParseCombiningCharacters(string str) { throw new ArgumentNullException(nameof(str)); } - Contract.EndContractBlock(); int len = str.Length; int[] result = new int[len]; diff --git a/src/mscorlib/shared/System/Globalization/TaiwanCalendar.cs b/src/mscorlib/shared/System/Globalization/TaiwanCalendar.cs index ec4188161a3f..c5161138de4a 100644 --- a/src/mscorlib/shared/System/Globalization/TaiwanCalendar.cs +++ b/src/mscorlib/shared/System/Globalization/TaiwanCalendar.cs @@ -4,7 +4,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.Contracts; namespace System.Globalization { @@ -160,7 +159,6 @@ public override int GetMonthsInYear(int year, int era) } - [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return (helper.GetWeekOfYear(time, rule, firstDayOfWeek)); @@ -265,7 +263,6 @@ public override int ToFourDigitYear(int year) throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedPosNum); } - Contract.EndContractBlock(); if (year > helper.MaxYear) { diff --git a/src/mscorlib/shared/System/Globalization/TaiwanLunisolarCalendar.cs b/src/mscorlib/shared/System/Globalization/TaiwanLunisolarCalendar.cs index 1e2ec62a710c..60e84f7f330f 100644 --- a/src/mscorlib/shared/System/Globalization/TaiwanLunisolarCalendar.cs +++ b/src/mscorlib/shared/System/Globalization/TaiwanLunisolarCalendar.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics.Contracts; namespace System.Globalization { @@ -270,7 +269,6 @@ internal override int GetYearInfo(int lunarYear, int index) MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR)); } - Contract.EndContractBlock(); return s_yinfo[lunarYear - MIN_LUNISOLAR_YEAR, index]; } diff --git a/src/mscorlib/shared/System/Globalization/ThaiBuddhistCalendar.cs b/src/mscorlib/shared/System/Globalization/ThaiBuddhistCalendar.cs index e1646bfa8ec7..4f8fd8f01942 100644 --- a/src/mscorlib/shared/System/Globalization/ThaiBuddhistCalendar.cs +++ b/src/mscorlib/shared/System/Globalization/ThaiBuddhistCalendar.cs @@ -4,7 +4,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.Contracts; namespace System.Globalization { @@ -122,7 +121,6 @@ public override int GetMonthsInYear(int year, int era) } - [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return (helper.GetWeekOfYear(time, rule, firstDayOfWeek)); @@ -226,7 +224,6 @@ public override int ToFourDigitYear(int year) throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } - Contract.EndContractBlock(); return (helper.ToFourDigitYear(year, this.TwoDigitYearMax)); } diff --git a/src/mscorlib/shared/System/Globalization/UmAlQuraCalendar.cs b/src/mscorlib/shared/System/Globalization/UmAlQuraCalendar.cs index 99b99d67c0e1..21a938f8f160 100644 --- a/src/mscorlib/shared/System/Globalization/UmAlQuraCalendar.cs +++ b/src/mscorlib/shared/System/Globalization/UmAlQuraCalendar.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Globalization { @@ -517,7 +516,6 @@ public override DateTime AddMonths(DateTime time, int months) -120000, 120000)); } - Contract.EndContractBlock(); // Get the date in UmAlQura calendar. int y = GetDatePart(time, DatePartYear); int m = GetDatePart(time, DatePartMonth); @@ -822,7 +820,6 @@ public override int TwoDigitYearMax MinCalendarYear, MaxCalendarYear)); } - Contract.EndContractBlock(); VerifyWritable(); // We allow year 99 to be set so that one can make ToFourDigitYearMax a no-op by setting TwoDigitYearMax to 99. twoDigitYearMax = value; @@ -838,7 +835,6 @@ public override int ToFourDigitYear(int year) throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } - Contract.EndContractBlock(); if (year < 100) { diff --git a/src/mscorlib/shared/System/Guid.cs b/src/mscorlib/shared/System/Guid.cs index 4a3855b1063b..496bc3532745 100644 --- a/src/mscorlib/shared/System/Guid.cs +++ b/src/mscorlib/shared/System/Guid.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -87,7 +86,6 @@ public Guid(int a, short b, short c, byte[] d) // Check that array is not too big if (d.Length != 8) throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "8"), nameof(d)); - Contract.EndContractBlock(); _a = a; _b = b; @@ -245,7 +243,6 @@ public Guid(string g) { throw new ArgumentNullException(nameof(g)); } - Contract.EndContractBlock(); GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.All); diff --git a/src/mscorlib/shared/System/IFormattable.cs b/src/mscorlib/shared/System/IFormattable.cs index 28a7d70571e6..1f2f7022ccb6 100644 --- a/src/mscorlib/shared/System/IFormattable.cs +++ b/src/mscorlib/shared/System/IFormattable.cs @@ -3,13 +3,11 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics.Contracts; namespace System { public interface IFormattable { - [Pure] String ToString(String format, IFormatProvider formatProvider); } } diff --git a/src/mscorlib/shared/System/IO/Error.cs b/src/mscorlib/shared/System/IO/Error.cs index 2aef895181f1..1e319a068039 100644 --- a/src/mscorlib/shared/System/IO/Error.cs +++ b/src/mscorlib/shared/System/IO/Error.cs @@ -6,14 +6,12 @@ using System.Runtime.InteropServices; using System.Text; using System.Globalization; -using System.Diagnostics.Contracts; namespace System.IO { /// /// Provides centralized methods for creating exceptions for System.IO.FileSystem. /// - [Pure] internal static class Error { internal static Exception GetStreamIsClosed() diff --git a/src/mscorlib/shared/System/IO/Path.cs b/src/mscorlib/shared/System/IO/Path.cs index 2676f0d2fe95..c9b9ed0cd972 100644 --- a/src/mscorlib/shared/System/IO/Path.cs +++ b/src/mscorlib/shared/System/IO/Path.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Text; namespace System.IO @@ -100,7 +99,6 @@ public static string GetDirectoryName(string path) // period (".") character of the extension except when you have a terminal period when you get string.Empty, such as ".exe" or // ".cpp". The returned value is null if the given path is // null or if the given path does not include an extension. - [Pure] public static string GetExtension(string path) { if (path == null) @@ -127,7 +125,6 @@ public static string GetExtension(string path) // Returns the name and extension parts of the given path. The resulting // string contains the characters of path that follow the last // separator in path. The resulting string is null if path is null. - [Pure] public static string GetFileName(string path) { if (path == null) @@ -138,7 +135,6 @@ public static string GetFileName(string path) return path.Substring(offset, count); } - [Pure] public static string GetFileNameWithoutExtension(string path) { if (path == null) @@ -194,7 +190,6 @@ public static bool IsPathFullyQualified(string path) // true if the characters that follow the last directory // separator ('\\' or '/') or volume separator (':') in the path include // a period (".") other than a terminal period. The result is false otherwise. - [Pure] public static bool HasExtension(string path) { if (path != null) @@ -218,7 +213,6 @@ public static string Combine(string path1, string path2) { if (path1 == null || path2 == null) throw new ArgumentNullException((path1 == null) ? nameof(path1) : nameof(path2)); - Contract.EndContractBlock(); PathInternal.CheckInvalidPathChars(path1); PathInternal.CheckInvalidPathChars(path2); @@ -230,7 +224,6 @@ public static string Combine(string path1, string path2, string path3) { if (path1 == null || path2 == null || path3 == null) throw new ArgumentNullException((path1 == null) ? nameof(path1) : (path2 == null) ? nameof(path2) : nameof(path3)); - Contract.EndContractBlock(); PathInternal.CheckInvalidPathChars(path1); PathInternal.CheckInvalidPathChars(path2); @@ -243,7 +236,6 @@ public static string Combine(string path1, string path2, string path3, string pa { if (path1 == null || path2 == null || path3 == null || path4 == null) throw new ArgumentNullException((path1 == null) ? nameof(path1) : (path2 == null) ? nameof(path2) : (path3 == null) ? nameof(path3) : nameof(path4)); - Contract.EndContractBlock(); PathInternal.CheckInvalidPathChars(path1); PathInternal.CheckInvalidPathChars(path2); @@ -259,7 +251,6 @@ public static string Combine(params string[] paths) { throw new ArgumentNullException(nameof(paths)); } - Contract.EndContractBlock(); int finalSize = 0; int firstComponent = 0; diff --git a/src/mscorlib/shared/System/IO/PinnedBufferMemoryStream.cs b/src/mscorlib/shared/System/IO/PinnedBufferMemoryStream.cs index e8f74dd05ca3..2bd1ef6b9537 100644 --- a/src/mscorlib/shared/System/IO/PinnedBufferMemoryStream.cs +++ b/src/mscorlib/shared/System/IO/PinnedBufferMemoryStream.cs @@ -17,7 +17,6 @@ using System; using System.Runtime.InteropServices; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.IO { diff --git a/src/mscorlib/shared/System/IO/UnmanagedMemoryStream.cs b/src/mscorlib/shared/System/IO/UnmanagedMemoryStream.cs index 76e6beb7a627..dc6f67bae90e 100644 --- a/src/mscorlib/shared/System/IO/UnmanagedMemoryStream.cs +++ b/src/mscorlib/shared/System/IO/UnmanagedMemoryStream.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; @@ -111,7 +110,6 @@ protected void Initialize(SafeBuffer buffer, long offset, long length, FileAcces { throw new ArgumentOutOfRangeException(nameof(access)); } - Contract.EndContractBlock(); if (_isOpen) { @@ -178,7 +176,6 @@ protected unsafe void Initialize(byte* pointer, long length, long capacity, File throw new ArgumentOutOfRangeException((length < 0) ? nameof(length) : nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum); if (length > capacity) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_LengthGreaterThanCapacity); - Contract.EndContractBlock(); // Check for wraparound. if (((byte*)((long)pointer + capacity)) < pointer) throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround); @@ -200,7 +197,6 @@ protected unsafe void Initialize(byte* pointer, long length, long capacity, File /// public override bool CanRead { - [Pure] get { return _isOpen && (_access & FileAccess.Read) != 0; } } @@ -209,7 +205,6 @@ public override bool CanRead /// public override bool CanSeek { - [Pure] get { return _isOpen; } } @@ -218,7 +213,6 @@ public override bool CanSeek /// public override bool CanWrite { - [Pure] get { return _isOpen && (_access & FileAccess.Write) != 0; } } @@ -298,14 +292,12 @@ public override long Position get { if (!CanSeek) throw Error.GetStreamIsClosed(); - Contract.EndContractBlock(); return Interlocked.Read(ref _position); } set { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); if (!CanSeek) throw Error.GetStreamIsClosed(); - Contract.EndContractBlock(); Interlocked.Exchange(ref _position, value); } @@ -452,7 +444,6 @@ public override Task ReadAsync(Byte[] buffer, Int32 offset, Int32 count, throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.EndContractBlock(); // contract validation copied from Read(...) if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); @@ -600,7 +591,6 @@ public override void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); if (_buffer != null) throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer); if (!_isOpen) throw Error.GetStreamIsClosed(); @@ -748,7 +738,6 @@ public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, Cancel throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.EndContractBlock(); // contract validation copied from Write(..) if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); diff --git a/src/mscorlib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs b/src/mscorlib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs index 2699912ea1db..90bb21ac5b28 100644 --- a/src/mscorlib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs +++ b/src/mscorlib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs @@ -14,7 +14,6 @@ using System; using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; @@ -82,7 +81,6 @@ public override int Capacity { return (int)_unmanagedStream.Capacity; } - [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. set { throw new IOException(SR.IO_FixedCapacity); @@ -156,7 +154,6 @@ public unsafe override void WriteTo(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream); - Contract.EndContractBlock(); byte[] buffer = ToArray(); @@ -193,7 +190,6 @@ public override Task CopyToAsync(Stream destination, Int32 bufferSize, Cancellat if (!destination.CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream); - Contract.EndContractBlock(); return _unmanagedStream.CopyToAsync(destination, bufferSize, cancellationToken); } diff --git a/src/mscorlib/shared/System/Int16.cs b/src/mscorlib/shared/System/Int16.cs index 6aaf4280d3a8..87004861cb3d 100644 --- a/src/mscorlib/shared/System/Int16.cs +++ b/src/mscorlib/shared/System/Int16.cs @@ -12,7 +12,6 @@ ** ===========================================================*/ -using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -80,32 +79,26 @@ public override int GetHashCode() public override String ToString() { - Contract.Ensures(Contract.Result() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { - Contract.Ensures(Contract.Result() != null); return ToString(format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return ToString(format, NumberFormatInfo.GetInstance(provider)); } private String ToString(String format, NumberFormatInfo info) { - Contract.Ensures(Contract.Result() != null); - if (m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x')) { uint temp = (uint)(m_value & 0x0000FFFF); diff --git a/src/mscorlib/shared/System/Int32.cs b/src/mscorlib/shared/System/Int32.cs index f5e832a274a8..d674e7b6bfae 100644 --- a/src/mscorlib/shared/System/Int32.cs +++ b/src/mscorlib/shared/System/Int32.cs @@ -12,7 +12,6 @@ ** ===========================================================*/ -using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -87,42 +86,32 @@ public override int GetHashCode() return m_value; } - [Pure] public override String ToString() { - Contract.Ensures(Contract.Result() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo); } - [Pure] public String ToString(String format) { - Contract.Ensures(Contract.Result() != null); return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo); } - [Pure] public String ToString(IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } - [Pure] public String ToString(String format, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider)); } - [Pure] public static int Parse(String s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } - [Pure] public static int Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -134,7 +123,6 @@ public static int Parse(String s, NumberStyles style) // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // - [Pure] public static int Parse(String s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -145,7 +133,6 @@ public static int Parse(String s, IFormatProvider provider) // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // - [Pure] public static int Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -162,7 +149,6 @@ public static int Parse(ReadOnlySpan s, NumberStyles style = NumberStyles. // Parses an integer from a String. Returns false rather // than throwing exceptin if input is invalid // - [Pure] public static bool TryParse(String s, out Int32 result) { if (s == null) @@ -177,7 +163,6 @@ public static bool TryParse(String s, out Int32 result) // Parses an integer from a String in the given style. Returns false rather // than throwing exceptin if input is invalid // - [Pure] public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int32 result) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -201,7 +186,6 @@ public static bool TryParse(ReadOnlySpan s, out int result, NumberStyles s // IConvertible implementation // - [Pure] public TypeCode GetTypeCode() { return TypeCode.Int32; diff --git a/src/mscorlib/shared/System/Int64.cs b/src/mscorlib/shared/System/Int64.cs index 785fa39fa511..e17c3ea6ed86 100644 --- a/src/mscorlib/shared/System/Int64.cs +++ b/src/mscorlib/shared/System/Int64.cs @@ -12,7 +12,6 @@ ** ===========================================================*/ -using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -86,25 +85,21 @@ public override int GetHashCode() public override String ToString() { - Contract.Ensures(Contract.Result() != null); return Number.FormatInt64(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatInt64(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { - Contract.Ensures(Contract.Result() != null); return Number.FormatInt64(m_value, format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatInt64(m_value, format, NumberFormatInfo.GetInstance(provider)); } diff --git a/src/mscorlib/shared/System/Math.cs b/src/mscorlib/shared/System/Math.cs index 6cfca945ae3d..174e2f6be510 100644 --- a/src/mscorlib/shared/System/Math.cs +++ b/src/mscorlib/shared/System/Math.cs @@ -13,6 +13,7 @@ //This class contains only static members and doesn't require serialization. +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime; using System.Runtime.CompilerServices; @@ -192,7 +193,7 @@ public static int Clamp(int value, int min, int max) { return max; } - + return value; } @@ -654,7 +655,6 @@ public static unsafe double Round(double value, int digits, MidpointRounding mod { throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode)); } - Contract.EndContractBlock(); if (Abs(value) < doubleRoundLimit) { @@ -761,52 +761,48 @@ public static unsafe double Truncate(double d) private static short AbsHelper(short value) { - Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); + Debug.Assert(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); if (value == short.MinValue) { throw new OverflowException(SR.Overflow_NegateTwosCompNum); } - Contract.EndContractBlock(); return ((short)(-value)); } private static int AbsHelper(int value) { - Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); + Debug.Assert(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); if (value == int.MinValue) { throw new OverflowException(SR.Overflow_NegateTwosCompNum); } - Contract.EndContractBlock(); return -value; } private static long AbsHelper(long value) { - Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); + Debug.Assert(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); if (value == long.MinValue) { throw new OverflowException(SR.Overflow_NegateTwosCompNum); } - Contract.EndContractBlock(); return -value; } private static sbyte AbsHelper(sbyte value) { - Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); + Debug.Assert(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); if (value == sbyte.MinValue) { throw new OverflowException(SR.Overflow_NegateTwosCompNum); } - Contract.EndContractBlock(); return ((sbyte)(-value)); } diff --git a/src/mscorlib/shared/System/MathF.cs b/src/mscorlib/shared/System/MathF.cs index f596c5a172a1..5b7e48b06208 100644 --- a/src/mscorlib/shared/System/MathF.cs +++ b/src/mscorlib/shared/System/MathF.cs @@ -10,7 +10,6 @@ //This class contains only static members and doesn't require serialization. -using System.Diagnostics.Contracts; using System.Runtime; using System.Runtime.CompilerServices; @@ -177,7 +176,6 @@ public static unsafe float Round(float x, int digits, MidpointRounding mode) { throw new ArgumentException(SR.Format(SR.Argument_InvalidEnum, mode, nameof(MidpointRounding)), nameof(mode)); } - Contract.EndContractBlock(); if (Abs(x) < singleRoundLimit) { diff --git a/src/mscorlib/shared/System/Resources/RuntimeResourceSet.cs b/src/mscorlib/shared/System/Resources/RuntimeResourceSet.cs index 41d7541c2441..eadc92c7f8e5 100644 --- a/src/mscorlib/shared/System/Resources/RuntimeResourceSet.cs +++ b/src/mscorlib/shared/System/Resources/RuntimeResourceSet.cs @@ -21,7 +21,6 @@ using System.Reflection; using System.Runtime.Versioning; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Resources { @@ -285,7 +284,6 @@ private Object GetObject(String key, bool ignoreCase, bool isString) throw new ArgumentNullException(nameof(key)); if (Reader == null || _resCache == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); - Contract.EndContractBlock(); Object value = null; ResourceLocator resLocation; diff --git a/src/mscorlib/shared/System/Runtime/Versioning/TargetFrameworkAttribute.cs b/src/mscorlib/shared/System/Runtime/Versioning/TargetFrameworkAttribute.cs index 54ccdf2c8154..a8190663821f 100644 --- a/src/mscorlib/shared/System/Runtime/Versioning/TargetFrameworkAttribute.cs +++ b/src/mscorlib/shared/System/Runtime/Versioning/TargetFrameworkAttribute.cs @@ -13,7 +13,6 @@ ===========================================================*/ using System; -using System.Diagnostics.Contracts; namespace System.Runtime.Versioning { @@ -28,7 +27,6 @@ public TargetFrameworkAttribute(String frameworkName) { if (frameworkName == null) throw new ArgumentNullException(nameof(frameworkName)); - Contract.EndContractBlock(); _frameworkName = frameworkName; } diff --git a/src/mscorlib/shared/System/SByte.cs b/src/mscorlib/shared/System/SByte.cs index c984767336f1..5b5c031d5f7d 100644 --- a/src/mscorlib/shared/System/SByte.cs +++ b/src/mscorlib/shared/System/SByte.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -74,32 +73,26 @@ public override int GetHashCode() // Provides a string representation of a byte. public override String ToString() { - Contract.Ensures(Contract.Result() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { - Contract.Ensures(Contract.Result() != null); return ToString(format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return ToString(format, NumberFormatInfo.GetInstance(provider)); } private String ToString(String format, NumberFormatInfo info) { - Contract.Ensures(Contract.Result() != null); - if (m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x')) { uint temp = (uint)(m_value & 0x000000FF); diff --git a/src/mscorlib/shared/System/Single.cs b/src/mscorlib/shared/System/Single.cs index 0be8cfbc372a..14f0ca49ff06 100644 --- a/src/mscorlib/shared/System/Single.cs +++ b/src/mscorlib/shared/System/Single.cs @@ -11,7 +11,6 @@ ** ===========================================================*/ -using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -40,7 +39,6 @@ public struct Single : IComparable, IConvertible, IFormattable, IComparableDetermines whether the specified value is finite (zero, subnormal, or normal). - [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsFinite(float f) @@ -50,7 +48,6 @@ public static bool IsFinite(float f) } /// Determines whether the specified value is infinite. - [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsInfinity(float f) @@ -60,7 +57,6 @@ public unsafe static bool IsInfinity(float f) } /// Determines whether the specified value is NaN. - [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNaN(float f) @@ -70,7 +66,6 @@ public unsafe static bool IsNaN(float f) } /// Determines whether the specified value is negative. - [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNegative(float f) @@ -80,7 +75,6 @@ public unsafe static bool IsNegative(float f) } /// Determines whether the specified value is negative infinity. - [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsNegativeInfinity(float f) @@ -89,7 +83,6 @@ public unsafe static bool IsNegativeInfinity(float f) } /// Determines whether the specified value is normal. - [Pure] [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called public unsafe static bool IsNormal(float f) @@ -100,7 +93,6 @@ public unsafe static bool IsNormal(float f) } /// Determines whether the specified value is positive infinity. - [Pure] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static bool IsPositiveInfinity(float f) @@ -109,7 +101,6 @@ public unsafe static bool IsPositiveInfinity(float f) } /// Determines whether the specified value is subnormal. - [Pure] [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called public unsafe static bool IsSubnormal(float f) @@ -236,25 +227,21 @@ public unsafe override int GetHashCode() public override String ToString() { - Contract.Ensures(Contract.Result() != null); return Number.FormatSingle(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatSingle(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { - Contract.Ensures(Contract.Result() != null); return Number.FormatSingle(m_value, format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider)); } diff --git a/src/mscorlib/shared/System/StringComparer.cs b/src/mscorlib/shared/System/StringComparer.cs index ad667ae29b03..73c013599da6 100644 --- a/src/mscorlib/shared/System/StringComparer.cs +++ b/src/mscorlib/shared/System/StringComparer.cs @@ -5,7 +5,6 @@ using System.Collections; using System.Collections.Generic; using System.Globalization; -using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System @@ -23,7 +22,6 @@ public static StringComparer InvariantCulture { get { - Contract.Ensures(Contract.Result() != null); return s_invariantCulture; } } @@ -32,7 +30,6 @@ public static StringComparer InvariantCultureIgnoreCase { get { - Contract.Ensures(Contract.Result() != null); return s_invariantCultureIgnoreCase; } } @@ -41,7 +38,6 @@ public static StringComparer CurrentCulture { get { - Contract.Ensures(Contract.Result() != null); return new CultureAwareComparer(CultureInfo.CurrentCulture, false); } } @@ -50,7 +46,6 @@ public static StringComparer CurrentCultureIgnoreCase { get { - Contract.Ensures(Contract.Result() != null); return new CultureAwareComparer(CultureInfo.CurrentCulture, true); } } @@ -59,7 +54,6 @@ public static StringComparer Ordinal { get { - Contract.Ensures(Contract.Result() != null); return s_ordinal; } } @@ -68,7 +62,6 @@ public static StringComparer OrdinalIgnoreCase { get { - Contract.Ensures(Contract.Result() != null); return s_ordinalIgnoreCase; } } @@ -101,8 +94,6 @@ public static StringComparer Create(CultureInfo culture, bool ignoreCase) { throw new ArgumentNullException(nameof(culture)); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return new CultureAwareComparer(culture, ignoreCase); } @@ -156,7 +147,6 @@ public int GetHashCode(object obj) { throw new ArgumentNullException(nameof(obj)); } - Contract.EndContractBlock(); string s = obj as string; if (s != null) @@ -279,7 +269,6 @@ public override int GetHashCode(string obj) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj); } - Contract.EndContractBlock(); if (_ignoreCase) { diff --git a/src/mscorlib/shared/System/Text/ASCIIEncoding.cs b/src/mscorlib/shared/System/Text/ASCIIEncoding.cs index f614fb768b92..2d2bf205ae7e 100644 --- a/src/mscorlib/shared/System/Text/ASCIIEncoding.cs +++ b/src/mscorlib/shared/System/Text/ASCIIEncoding.cs @@ -4,7 +4,6 @@ using System; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Text { @@ -66,7 +65,6 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // If no input, return 0, avoid fixed empty array problem if (count == 0) @@ -87,7 +85,6 @@ public override unsafe int GetByteCount(String chars) // Validate input if (chars==null) throw new ArgumentNullException("chars"); - Contract.EndContractBlock(); fixed (char* pChars = chars) return GetByteCount(pChars, chars.Length, null); @@ -106,7 +103,6 @@ public override unsafe int GetByteCount(char* chars, int count) if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Call it with empty encoder return GetByteCount(chars, count, null); @@ -131,7 +127,6 @@ public override unsafe int GetBytes(String chars, int charIndex, int charCount, if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); int byteCount = bytes.Length - byteIndex; @@ -172,7 +167,6 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) @@ -203,7 +197,6 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return GetBytes(chars, charCount, bytes, byteCount, null); } @@ -227,7 +220,6 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count) if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // If no input just return 0, fixed doesn't like 0 length arrays if (count == 0) @@ -251,7 +243,6 @@ public override unsafe int GetCharCount(byte* bytes, int count) if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return GetCharCount(bytes, count, null); } @@ -276,7 +267,6 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); // If no input, return 0 & avoid fixed problem if (byteCount == 0) @@ -307,7 +297,6 @@ public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return GetChars(bytes, byteCount, chars, charCount, null); } @@ -332,7 +321,6 @@ public override unsafe String GetString(byte[] bytes, int byteIndex, int byteCou if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // Avoid problems with empty input buffer if (byteCount == 0) return String.Empty; @@ -910,7 +898,6 @@ public override int GetMaxByteCount(int charCount) if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Characters would be # of characters + 1 in case high surrogate is ? * max fallback long byteCount = (long)charCount + 1; @@ -931,7 +918,6 @@ public override int GetMaxCharCount(int byteCount) if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Just return length, SBCS stay the same length because they don't map to surrogate long charCount = (long)byteCount; diff --git a/src/mscorlib/shared/System/Text/Decoder.cs b/src/mscorlib/shared/System/Text/Decoder.cs index 82d33d518cc4..8dccaacd98a6 100644 --- a/src/mscorlib/shared/System/Text/Decoder.cs +++ b/src/mscorlib/shared/System/Text/Decoder.cs @@ -5,7 +5,6 @@ using System.Text; using System; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Text { @@ -42,7 +41,6 @@ public DecoderFallback Fallback { if (value == null) throw new ArgumentNullException(nameof(value)); - Contract.EndContractBlock(); // Can't change fallback if buffer is wrong if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) @@ -123,7 +121,6 @@ public virtual unsafe int GetCharCount(byte* bytes, int count, bool flush) if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); byte[] arrbyte = new byte[count]; int index; @@ -195,7 +192,6 @@ public virtual unsafe int GetChars(byte* bytes, int byteCount, if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Get the byte array to convert byte[] arrByte = new byte[byteCount]; @@ -274,7 +270,6 @@ public virtual void Convert(byte[] bytes, int byteIndex, int byteCount, if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); bytesUsed = byteCount; @@ -319,7 +314,6 @@ public virtual unsafe void Convert(byte* bytes, int byteCount, if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Get ready to do it bytesUsed = byteCount; diff --git a/src/mscorlib/shared/System/Text/DecoderNLS.cs b/src/mscorlib/shared/System/Text/DecoderNLS.cs index ef85200d552d..098730eed436 100644 --- a/src/mscorlib/shared/System/Text/DecoderNLS.cs +++ b/src/mscorlib/shared/System/Text/DecoderNLS.cs @@ -5,7 +5,6 @@ using System.Runtime.Serialization; using System.Text; using System; -using System.Diagnostics.Contracts; namespace System.Text { @@ -67,7 +66,6 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // Avoid null fixed problem if (bytes.Length == 0) @@ -88,7 +86,6 @@ public unsafe override int GetCharCount(byte* bytes, int count, bool flush) if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Remember the flush _mustFlush = flush; @@ -124,7 +121,6 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); // Avoid empty input fixed problem if (bytes.Length == 0) @@ -153,7 +149,6 @@ public unsafe override int GetChars(byte* bytes, int byteCount, if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Remember our flush _mustFlush = flush; @@ -190,7 +185,6 @@ public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount, throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // Avoid empty input problem if (bytes.Length == 0) @@ -223,7 +217,6 @@ public unsafe override void Convert(byte* bytes, int byteCount, if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // We don't want to throw _mustFlush = flush; diff --git a/src/mscorlib/shared/System/Text/DecoderReplacementFallback.cs b/src/mscorlib/shared/System/Text/DecoderReplacementFallback.cs index 8a8d550c848e..422b80bb2fcf 100644 --- a/src/mscorlib/shared/System/Text/DecoderReplacementFallback.cs +++ b/src/mscorlib/shared/System/Text/DecoderReplacementFallback.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Text { @@ -21,7 +20,6 @@ public DecoderReplacementFallback(String replacement) { if (replacement == null) throw new ArgumentNullException(nameof(replacement)); - Contract.EndContractBlock(); // Make sure it doesn't have bad surrogate pairs bool bFoundHigh = false; diff --git a/src/mscorlib/shared/System/Text/Encoder.cs b/src/mscorlib/shared/System/Text/Encoder.cs index 79a633f1ffd1..167060859967 100644 --- a/src/mscorlib/shared/System/Text/Encoder.cs +++ b/src/mscorlib/shared/System/Text/Encoder.cs @@ -5,7 +5,6 @@ using System.Text; using System; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Text { @@ -42,7 +41,6 @@ public EncoderFallback Fallback { if (value == null) throw new ArgumentNullException(nameof(value)); - Contract.EndContractBlock(); // Can't change fallback if buffer is wrong if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) @@ -121,7 +119,6 @@ public virtual unsafe int GetByteCount(char* chars, int count, bool flush) if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); char[] arrChar = new char[count]; int index; @@ -190,7 +187,6 @@ public virtual unsafe int GetBytes(char* chars, int charCount, if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Get the char array to convert char[] arrChar = new char[charCount]; @@ -268,7 +264,6 @@ public virtual void Convert(char[] chars, int charIndex, int charCount, if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); charsUsed = charCount; @@ -313,7 +308,6 @@ public virtual unsafe void Convert(char* chars, int charCount, if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Get ready to do it charsUsed = charCount; diff --git a/src/mscorlib/shared/System/Text/EncoderBestFitFallback.cs b/src/mscorlib/shared/System/Text/EncoderBestFitFallback.cs index a8c288b6335c..7f3be2a7a694 100644 --- a/src/mscorlib/shared/System/Text/EncoderBestFitFallback.cs +++ b/src/mscorlib/shared/System/Text/EncoderBestFitFallback.cs @@ -7,7 +7,6 @@ // using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Globalization; using System.Threading; @@ -123,7 +122,6 @@ public override bool Fallback(char charUnknownHigh, char charUnknownLow, int ind throw new ArgumentOutOfRangeException(nameof(charUnknownLow), SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF)); - Contract.EndContractBlock(); // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. 0 is processing last character, < 0 is not falling back diff --git a/src/mscorlib/shared/System/Text/EncoderExceptionFallback.cs b/src/mscorlib/shared/System/Text/EncoderExceptionFallback.cs index 71426e5f312d..4c71916901fd 100644 --- a/src/mscorlib/shared/System/Text/EncoderExceptionFallback.cs +++ b/src/mscorlib/shared/System/Text/EncoderExceptionFallback.cs @@ -4,7 +4,6 @@ using System; using System.Runtime.Serialization; -using System.Diagnostics.Contracts; namespace System.Text { @@ -68,7 +67,6 @@ public override bool Fallback(char charUnknownHigh, char charUnknownLow, int ind throw new ArgumentOutOfRangeException(nameof(charUnknownLow), SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF)); } - Contract.EndContractBlock(); int iTemp = Char.ConvertToUtf32(charUnknownHigh, charUnknownLow); @@ -143,7 +141,6 @@ internal EncoderFallbackException( throw new ArgumentOutOfRangeException(nameof(CharUnknownLow), SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF)); } - Contract.EndContractBlock(); _charUnknownHigh = charUnknownHigh; _charUnknownLow = charUnknownLow; diff --git a/src/mscorlib/shared/System/Text/EncoderNLS.cs b/src/mscorlib/shared/System/Text/EncoderNLS.cs index 28a1b8b9b30d..f8ff86d98598 100644 --- a/src/mscorlib/shared/System/Text/EncoderNLS.cs +++ b/src/mscorlib/shared/System/Text/EncoderNLS.cs @@ -4,7 +4,6 @@ using System.Text; using System; -using System.Diagnostics.Contracts; namespace System.Text { @@ -63,7 +62,6 @@ public override unsafe int GetByteCount(char[] chars, int index, int count, bool if (chars.Length - index < count) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // Avoid empty input problem if (chars.Length == 0) @@ -88,7 +86,6 @@ public unsafe override int GetByteCount(char* chars, int count, bool flush) if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); _mustFlush = flush; _throwOnOverflow = true; @@ -114,7 +111,6 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); if (chars.Length == 0) chars = new char[1]; @@ -142,7 +138,6 @@ public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); _mustFlush = flush; _throwOnOverflow = true; @@ -176,7 +171,6 @@ public override unsafe void Convert(char[] chars, int charIndex, int charCount, throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // Avoid empty input problem if (chars.Length == 0) @@ -208,7 +202,6 @@ public override unsafe void Convert(char* chars, int charCount, if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // We don't want to throw _mustFlush = flush; diff --git a/src/mscorlib/shared/System/Text/EncoderReplacementFallback.cs b/src/mscorlib/shared/System/Text/EncoderReplacementFallback.cs index 22d094ce5cd2..a1d0bbcd95ae 100644 --- a/src/mscorlib/shared/System/Text/EncoderReplacementFallback.cs +++ b/src/mscorlib/shared/System/Text/EncoderReplacementFallback.cs @@ -5,7 +5,6 @@ using System; using System.Runtime; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Text { @@ -24,7 +23,6 @@ public EncoderReplacementFallback(String replacement) // Must not be null if (replacement == null) throw new ArgumentNullException(nameof(replacement)); - Contract.EndContractBlock(); // Make sure it doesn't have bad surrogate pairs bool bFoundHigh = false; @@ -153,7 +151,6 @@ public override bool Fallback(char charUnknownHigh, char charUnknownLow, int ind if (!Char.IsLowSurrogate(charUnknownLow)) throw new ArgumentOutOfRangeException(nameof(charUnknownLow), SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF)); - Contract.EndContractBlock(); // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. diff --git a/src/mscorlib/shared/System/Text/Encoding.cs b/src/mscorlib/shared/System/Text/Encoding.cs index bf8cb03db2b8..8e4d29d24cec 100644 --- a/src/mscorlib/shared/System/Text/Encoding.cs +++ b/src/mscorlib/shared/System/Text/Encoding.cs @@ -4,7 +4,6 @@ using System.Diagnostics; using System.Globalization; -using System.Diagnostics.Contracts; using System.Threading; using System.Runtime.Serialization; using System.Diagnostics.CodeAnalysis; @@ -178,7 +177,6 @@ protected Encoding(int codePage) { throw new ArgumentOutOfRangeException(nameof(codePage)); } - Contract.EndContractBlock(); // Remember code page _codePage = codePage; @@ -197,7 +195,6 @@ protected Encoding(int codePage, EncoderFallback encoderFallback, DecoderFallbac { throw new ArgumentOutOfRangeException(nameof(codePage)); } - Contract.EndContractBlock(); // Remember code page _codePage = codePage; @@ -220,13 +217,11 @@ internal virtual void SetDefaultFallbacks() // dstEncoding, and the returned value is a new byte array // containing the result of the conversion. // - [Pure] public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes) { if (bytes == null) throw new ArgumentNullException(nameof(bytes)); - Contract.Ensures(Contract.Result() != null); return Convert(srcEncoding, dstEncoding, bytes, 0, bytes.Length); } @@ -236,7 +231,6 @@ public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, // index index from srcEncoding to dstEncoding, and // returns a new byte array containing the result of the conversion. // - [Pure] public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes, int index, int count) { @@ -250,7 +244,6 @@ public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); } - Contract.Ensures(Contract.Result() != null); return dstEncoding.GetBytes(srcEncoding.GetChars(bytes, index, count)); } @@ -261,7 +254,6 @@ public static void RegisterProvider(EncodingProvider provider) EncodingProvider.AddProvider(provider); } - [Pure] public static Encoding GetEncoding(int codepage) { Encoding result = EncodingProvider.GetEncodingFromProvider(codepage); @@ -280,7 +272,6 @@ public static Encoding GetEncoding(int codepage) nameof(codepage), SR.Format(SR.ArgumentOutOfRange_Range, 0, 65535)); } - Contract.EndContractBlock(); switch (codepage) { @@ -312,7 +303,6 @@ public static Encoding GetEncoding(int codepage) return UTF8; } - [Pure] public static Encoding GetEncoding(int codepage, EncoderFallback encoderFallback, DecoderFallback decoderFallback) { @@ -334,7 +324,6 @@ public static Encoding GetEncoding(int codepage, // Returns an Encoding object for a given name or a given code page value. // - [Pure] public static Encoding GetEncoding(String name) { Encoding baseEncoding = EncodingProvider.GetEncodingFromProvider(name); @@ -352,7 +341,6 @@ public static Encoding GetEncoding(String name) // Returns an Encoding object for a given name or a given code page value. // - [Pure] public static Encoding GetEncoding(String name, EncoderFallback encoderFallback, DecoderFallback decoderFallback) { @@ -370,13 +358,11 @@ public static Encoding GetEncoding(String name, } // Return a list of all EncodingInfo objects describing all of our encodings - [Pure] public static EncodingInfo[] GetEncodings() { return EncodingTable.GetEncodings(); } - [Pure] public virtual byte[] GetPreamble() { return Array.Empty(); @@ -590,7 +576,6 @@ public EncoderFallback EncoderFallback if (value == null) throw new ArgumentNullException(nameof(value)); - Contract.EndContractBlock(); encoderFallback = value; } @@ -611,7 +596,6 @@ public DecoderFallback DecoderFallback if (value == null) throw new ArgumentNullException(nameof(value)); - Contract.EndContractBlock(); decoderFallback = value; } @@ -650,7 +634,6 @@ public bool IsReadOnly // Returns the number of bytes required to encode the given character // array. // - [Pure] public virtual int GetByteCount(char[] chars) { if (chars == null) @@ -658,17 +641,14 @@ public virtual int GetByteCount(char[] chars) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); } - Contract.EndContractBlock(); return GetByteCount(chars, 0, chars.Length); } - [Pure] public virtual int GetByteCount(String s) { if (s == null) throw new ArgumentNullException(nameof(s)); - Contract.EndContractBlock(); char[] chars = s.ToCharArray(); return GetByteCount(chars, 0, chars.Length); @@ -677,12 +657,10 @@ public virtual int GetByteCount(String s) // Returns the number of bytes required to encode a range of characters in // a character array. // - [Pure] public abstract int GetByteCount(char[] chars, int index, int count); // Returns the number of bytes required to encode a string range. // - [Pure] public int GetByteCount(string s, int index, int count) { if (s == null) @@ -697,7 +675,6 @@ public int GetByteCount(string s, int index, int count) if (index > s.Length - count) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexCount); - Contract.EndContractBlock(); unsafe { @@ -712,7 +689,6 @@ public int GetByteCount(string s, int index, int count) // unfortunately for existing overrides, it has to call the [] version, // which is really slow, so this method should be avoided if you're calling // a 3rd party encoding. - [Pure] [CLSCompliant(false)] public virtual unsafe int GetByteCount(char* chars, int count) { @@ -724,7 +700,6 @@ public virtual unsafe int GetByteCount(char* chars, int count) if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); char[] arrChar = new char[count]; int index; @@ -756,7 +731,6 @@ internal virtual unsafe int GetByteCount(char* chars, int count, EncoderNLS enco // Returns a byte array containing the encoded representation of the given // character array. // - [Pure] public virtual byte[] GetBytes(char[] chars) { if (chars == null) @@ -764,14 +738,12 @@ public virtual byte[] GetBytes(char[] chars) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); } - Contract.EndContractBlock(); return GetBytes(chars, 0, chars.Length); } // Returns a byte array containing the encoded representation of a range // of characters in a character array. // - [Pure] public virtual byte[] GetBytes(char[] chars, int index, int count) { byte[] result = new byte[GetByteCount(chars, index, count)]; @@ -794,13 +766,11 @@ public abstract int GetBytes(char[] chars, int charIndex, int charCount, // Returns a byte array containing the encoded representation of the given // string. // - [Pure] public virtual byte[] GetBytes(String s) { if (s == null) throw new ArgumentNullException(nameof(s), SR.ArgumentNull_String); - Contract.EndContractBlock(); int byteCount = GetByteCount(s); byte[] bytes = new byte[byteCount]; @@ -812,7 +782,6 @@ public virtual byte[] GetBytes(String s) // Returns a byte array containing the encoded representation of the given // string range. // - [Pure] public byte[] GetBytes(string s, int index, int count) { if (s == null) @@ -827,7 +796,6 @@ public byte[] GetBytes(string s, int index, int count) if (index > s.Length - count) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexCount); - Contract.EndContractBlock(); unsafe { @@ -853,7 +821,6 @@ public virtual int GetBytes(String s, int charIndex, int charCount, { if (s == null) throw new ArgumentNullException(nameof(s)); - Contract.EndContractBlock(); return GetBytes(s.ToCharArray(), charIndex, charCount, bytes, byteIndex); } @@ -894,7 +861,6 @@ public virtual unsafe int GetBytes(char* chars, int charCount, if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Get the char array to convert char[] arrChar = new char[charCount]; @@ -938,7 +904,6 @@ public virtual unsafe int GetBytes(ReadOnlySpan chars, Span bytes) // Returns the number of characters produced by decoding the given byte // array. // - [Pure] public virtual int GetCharCount(byte[] bytes) { if (bytes == null) @@ -946,19 +911,16 @@ public virtual int GetCharCount(byte[] bytes) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); } - Contract.EndContractBlock(); return GetCharCount(bytes, 0, bytes.Length); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // - [Pure] public abstract int GetCharCount(byte[] bytes, int index, int count); // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implementation) - [Pure] [CLSCompliant(false)] public virtual unsafe int GetCharCount(byte* bytes, int count) { @@ -970,7 +932,6 @@ public virtual unsafe int GetCharCount(byte* bytes, int count) if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); byte[] arrbyte = new byte[count]; int index; @@ -999,7 +960,6 @@ internal virtual unsafe int GetCharCount(byte* bytes, int count, DecoderNLS deco // Returns a character array containing the decoded representation of a // given byte array. // - [Pure] public virtual char[] GetChars(byte[] bytes) { if (bytes == null) @@ -1007,14 +967,12 @@ public virtual char[] GetChars(byte[] bytes) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); } - Contract.EndContractBlock(); return GetChars(bytes, 0, bytes.Length); } // Returns a character array containing the decoded representation of a // range of bytes in a byte array. // - [Pure] public virtual char[] GetChars(byte[] bytes, int index, int count) { char[] result = new char[GetCharCount(bytes, index, count)]; @@ -1065,7 +1023,6 @@ public virtual unsafe int GetChars(byte* bytes, int byteCount, if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Get the byte array to convert byte[] arrByte = new byte[byteCount]; @@ -1123,7 +1080,6 @@ public unsafe string GetString(byte* bytes, int byteCount) if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return String.CreateStringFromEncoding(bytes, byteCount, this); } @@ -1152,13 +1108,11 @@ public virtual int CodePage // IsAlwaysNormalized // Returns true if the encoding is always normalized for the specified encoding form - [Pure] public bool IsAlwaysNormalized() { return this.IsAlwaysNormalized(NormalizationForm.FormC); } - [Pure] public virtual bool IsAlwaysNormalized(NormalizationForm form) { // Assume false unless the encoding knows otherwise @@ -1214,7 +1168,6 @@ public virtual Encoder GetEncoder() // WARNING: If you're using something besides the default replacement encoder fallback, // then you could have more bytes than this returned from an actual call to GetBytes(). // - [Pure] public abstract int GetMaxByteCount(int charCount); // Returns the maximum number of characters produced by decoding a given @@ -1225,19 +1178,16 @@ public virtual Encoder GetEncoder() // exceptions will occur if buffers are sized according to the results of // this method. // - [Pure] public abstract int GetMaxCharCount(int byteCount); // Returns a string containing the decoded representation of a given byte // array. // - [Pure] public virtual String GetString(byte[] bytes) { if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); - Contract.EndContractBlock(); return GetString(bytes, 0, bytes.Length); } @@ -1247,7 +1197,6 @@ public virtual String GetString(byte[] bytes) // // Internally we override this for performance // - [Pure] public virtual String GetString(byte[] bytes, int index, int count) { return new String(GetChars(bytes, index, count)); @@ -1393,7 +1342,6 @@ public override int GetByteCount(char[] chars, int index, int count, bool flush) return _encoding.GetByteCount(chars, index, count); } - [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public unsafe override int GetByteCount(char* chars, int count, bool flush) { return _encoding.GetByteCount(chars, count); @@ -1425,7 +1373,6 @@ public override int GetBytes(char[] chars, int charIndex, int charCount, return _encoding.GetBytes(chars, charIndex, charCount, bytes, byteIndex); } - [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { @@ -1464,7 +1411,6 @@ public override int GetCharCount(byte[] bytes, int index, int count, bool flush) return _encoding.GetCharCount(bytes, index, count); } - [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public unsafe override int GetCharCount(byte* bytes, int count, bool flush) { // By default just call the encoding version, no flush by default @@ -1500,7 +1446,6 @@ public override int GetChars(byte[] bytes, int byteIndex, int byteCount, return _encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex); } - [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { diff --git a/src/mscorlib/shared/System/Text/EncodingNLS.cs b/src/mscorlib/shared/System/Text/EncodingNLS.cs index 835bf8fb372d..5059407ab9de 100644 --- a/src/mscorlib/shared/System/Text/EncodingNLS.cs +++ b/src/mscorlib/shared/System/Text/EncodingNLS.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics.Contracts; using System.Collections; using System.Globalization; using System.Threading; @@ -47,7 +46,6 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // If no input, return 0, avoid fixed empty array problem if (count == 0) @@ -67,7 +65,6 @@ public override unsafe int GetByteCount(String s) // Validate input if (s==null) throw new ArgumentNullException("s"); - Contract.EndContractBlock(); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); @@ -84,7 +81,6 @@ public override unsafe int GetByteCount(char* chars, int count) if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Call it with empty encoder return GetByteCount(chars, count, null); @@ -108,7 +104,6 @@ public override unsafe int GetBytes(String s, int charIndex, int charCount, if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); int byteCount = bytes.Length - byteIndex; @@ -148,7 +143,6 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) @@ -177,7 +171,6 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return GetBytes(chars, charCount, bytes, byteCount, null); } @@ -200,7 +193,6 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count) if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // If no input just return 0, fixed doesn't like 0 length arrays if (count == 0) @@ -222,7 +214,6 @@ public override unsafe int GetCharCount(byte* bytes, int count) if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return GetCharCount(bytes, count, null); } @@ -246,7 +237,6 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); // If no input, return 0 & avoid fixed problem if (byteCount == 0) @@ -275,7 +265,6 @@ public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return GetChars(bytes, byteCount, chars, charCount, null); } @@ -298,7 +287,6 @@ public override unsafe String GetString(byte[] bytes, int index, int count) if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // Avoid problems with empty input buffer if (count == 0) return String.Empty; diff --git a/src/mscorlib/shared/System/Text/Latin1Encoding.cs b/src/mscorlib/shared/System/Text/Latin1Encoding.cs index 679698d926c4..335eb76e3cb2 100644 --- a/src/mscorlib/shared/System/Text/Latin1Encoding.cs +++ b/src/mscorlib/shared/System/Text/Latin1Encoding.cs @@ -4,7 +4,6 @@ using System; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Text { @@ -420,7 +419,6 @@ public override int GetMaxByteCount(int charCount) if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Characters would be # of characters + 1 in case high surrogate is ? * max fallback long byteCount = (long)charCount + 1; @@ -440,7 +438,6 @@ public override int GetMaxCharCount(int byteCount) if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Just return length, SBCS stay the same length because they don't map to surrogate long charCount = (long)byteCount; diff --git a/src/mscorlib/shared/System/Text/StringBuilder.cs b/src/mscorlib/shared/System/Text/StringBuilder.cs index a73e6757d41f..f5003d812450 100644 --- a/src/mscorlib/shared/System/Text/StringBuilder.cs +++ b/src/mscorlib/shared/System/Text/StringBuilder.cs @@ -12,7 +12,6 @@ using System.Threading; using System.Globalization; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Collections.Generic; namespace System.Text @@ -134,7 +133,6 @@ public StringBuilder(string value, int startIndex, int length, int capacity) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); } - Contract.EndContractBlock(); if (value == null) { @@ -183,7 +181,6 @@ public StringBuilder(int capacity, int maxCapacity) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.Format(SR.ArgumentOutOfRange_MustBePositive, nameof(capacity))); } - Contract.EndContractBlock(); if (capacity == 0) { @@ -200,7 +197,6 @@ private StringBuilder(SerializationInfo info, StreamingContext context) { throw new ArgumentNullException(nameof(info)); } - Contract.EndContractBlock(); int persistedCapacity = 0; string persistedString = null; @@ -265,7 +261,6 @@ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext contex { throw new ArgumentNullException(nameof(info)); } - Contract.EndContractBlock(); AssertInvariants(); info.AddValue(MaxCapacityField, m_MaxCapacity); @@ -321,7 +316,6 @@ public int Capacity { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity); } - Contract.EndContractBlock(); if (Capacity != value) { @@ -352,7 +346,6 @@ public int EnsureCapacity(int capacity) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity); } - Contract.EndContractBlock(); if (Capacity < capacity) Capacity = capacity; @@ -410,8 +403,6 @@ public override String ToString() /// The number of characters to read in this builder. public string ToString(int startIndex, int length) { - Contract.Ensures(Contract.Result() != null); - int currentLength = this.Length; if (startIndex < 0) { @@ -496,7 +487,6 @@ public int Length { get { - Contract.Ensures(Contract.Result() >= 0); return m_ChunkOffset + m_ChunkLength; } set @@ -511,7 +501,6 @@ public int Length { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity); } - Contract.EndContractBlock(); int originalCapacity = Capacity; @@ -612,8 +601,6 @@ public StringBuilder Append(char value, int repeatCount) { throw new ArgumentOutOfRangeException(nameof(repeatCount), SR.ArgumentOutOfRange_NegativeCount); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); if (repeatCount == 0) { @@ -666,8 +653,6 @@ public StringBuilder Append(char[] value, int startIndex, int charCount) { throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GenericPositive); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); if (value == null) { @@ -705,8 +690,6 @@ public StringBuilder Append(char[] value, int startIndex, int charCount) /// The string to append. public StringBuilder Append(String value) { - Contract.Ensures(Contract.Result() != null); - if (value != null) { // We could have just called AppendHelper here; this is a hand-specialization of that code. @@ -776,7 +759,6 @@ public StringBuilder Append(string value, int startIndex, int count) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GenericPositive); } - Contract.Ensures(Contract.Result() != null); if (value == null) { @@ -831,7 +813,6 @@ public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, in { throw new ArgumentException(SR.ArgumentOutOfRange_OffsetOut); } - Contract.EndContractBlock(); CopyTo(sourceIndex, new Span(destination).Slice(destinationIndex), count); } @@ -852,7 +833,6 @@ public void CopyTo(int sourceIndex, Span destination, int count) { throw new ArgumentException(SR.Arg_LongerThanSrcString); } - Contract.EndContractBlock(); AssertInvariants(); @@ -896,8 +876,6 @@ public StringBuilder Insert(int index, String value, int count) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); int currentLength = Length; if ((uint)index > (uint)currentLength) @@ -959,8 +937,6 @@ public StringBuilder Remove(int startIndex, int length) { throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); if (Length == length && startIndex == 0) { @@ -987,8 +963,6 @@ public StringBuilder Remove(int startIndex, int length) public StringBuilder Append(char value) { - Contract.Ensures(Contract.Result() != null); - if (m_ChunkLength < m_ChunkChars.Length) { m_ChunkChars[m_ChunkLength++] = value; @@ -1170,8 +1144,6 @@ public StringBuilder Insert(int index, String value) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); if (value != null) { @@ -1195,8 +1167,6 @@ public StringBuilder Insert(int index, String value) public StringBuilder Insert(int index, char value) { - Contract.Ensures(Contract.Result() != null); - unsafe { Insert(index, &value, 1); @@ -1210,8 +1180,6 @@ public StringBuilder Insert(int index, char[] value) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); if (value != null) Insert(index, value, 0, value.Length); @@ -1220,8 +1188,6 @@ public StringBuilder Insert(int index, char[] value) public StringBuilder Insert(int index, char[] value, int startIndex, int charCount) { - Contract.Ensures(Contract.Result() != null); - int currentLength = Length; if ((uint)index > (uint)currentLength) { @@ -1286,9 +1252,6 @@ public StringBuilder Insert(int index, char[] value, int startIndex, int charCou public StringBuilder Insert(int index, ReadOnlySpan value) { - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); - if ((uint)index > (uint)Length) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); @@ -1320,8 +1283,6 @@ public StringBuilder AppendFormat(String format, params Object[] args) string paramName = (format == null) ? nameof(format) : nameof(args); throw new ArgumentNullException(paramName); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return AppendFormatHelper(null, format, new ParamsArray(args)); } @@ -1341,8 +1302,6 @@ public StringBuilder AppendFormat(IFormatProvider provider, String format, param string paramName = (format == null) ? nameof(format) : nameof(args); throw new ArgumentNullException(paramName); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return AppendFormatHelper(provider, format, new ParamsArray(args)); } @@ -1362,8 +1321,6 @@ internal StringBuilder AppendFormatHelper(IFormatProvider provider, String forma { throw new ArgumentNullException(nameof(format)); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); int pos = 0; int len = format.Length; @@ -1665,8 +1622,6 @@ public bool Equals(StringBuilder sb) /// public StringBuilder Replace(String oldValue, String newValue, int startIndex, int count) { - Contract.Ensures(Contract.Result() != null); - int currentLength = Length; if ((uint)startIndex > (uint)currentLength) { @@ -1762,8 +1717,6 @@ public StringBuilder Replace(char oldChar, char newChar) /// The number of characters to read in this builder. public StringBuilder Replace(char oldChar, char newChar, int startIndex, int count) { - Contract.Ensures(Contract.Result() != null); - int currentLength = Length; if ((uint)startIndex > (uint)currentLength) { @@ -2125,8 +2078,8 @@ private StringBuilder FindChunkForByte(int byteIndex) /// private void ExpandByABlock(int minBlockCharCount) { - Contract.Requires(Capacity == Length, $"{nameof(ExpandByABlock)} should only be called when there is no space left."); - Contract.Requires(minBlockCharCount > 0); + Debug.Assert(Capacity == Length, nameof(ExpandByABlock) + " should only be called when there is no space left."); + Debug.Assert(minBlockCharCount > 0); AssertInvariants(); diff --git a/src/mscorlib/shared/System/Text/UTF32Encoding.cs b/src/mscorlib/shared/System/Text/UTF32Encoding.cs index 260518e21c66..a666c25627e9 100644 --- a/src/mscorlib/shared/System/Text/UTF32Encoding.cs +++ b/src/mscorlib/shared/System/Text/UTF32Encoding.cs @@ -8,7 +8,6 @@ using System; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Globalization; namespace System.Text @@ -110,7 +109,6 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // If no input, return 0, avoid fixed empty array problem if (count == 0) @@ -131,7 +129,6 @@ public override unsafe int GetByteCount(String s) // Validate input if (s==null) throw new ArgumentNullException("s"); - Contract.EndContractBlock(); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); @@ -150,7 +147,6 @@ public override unsafe int GetByteCount(char* chars, int count) if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Call it with empty encoder return GetByteCount(chars, count, null); @@ -175,7 +171,6 @@ public override unsafe int GetBytes(String s, int charIndex, int charCount, if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); int byteCount = bytes.Length - byteIndex; @@ -216,7 +211,6 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) @@ -247,7 +241,6 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return GetBytes(chars, charCount, bytes, byteCount, null); } @@ -271,7 +264,6 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count) if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // If no input just return 0, fixed doesn't like 0 length arrays. if (count == 0) @@ -295,7 +287,6 @@ public override unsafe int GetCharCount(byte* bytes, int count) if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return GetCharCount(bytes, count, null); } @@ -320,7 +311,6 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); // If no input, return 0 & avoid fixed problem if (byteCount == 0) @@ -351,7 +341,6 @@ public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return GetChars(bytes, byteCount, chars, charCount, null); } @@ -375,7 +364,6 @@ public override unsafe String GetString(byte[] bytes, int index, int count) if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // Avoid problems with empty input buffer if (count == 0) return String.Empty; @@ -960,7 +948,6 @@ internal override unsafe int GetChars(byte* bytes, int byteCount, if (!fallbackResult) { - // Couldn't fallback, throw or wait til next time // We either read enough bytes for bytes-=4 to work, or we're // going to throw in ThrowCharsOverflow because chars == charStart @@ -1114,7 +1101,6 @@ public override int GetMaxByteCount(int charCount) if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback long byteCount = (long)charCount + 1; @@ -1137,7 +1123,6 @@ public override int GetMaxCharCount(int byteCount) if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // A supplementary character becomes 2 surrogate characters, so 4 input bytes becomes 2 chars, // plus we may have 1 surrogate char left over if the decoder has 3 bytes in it already for a non-bmp char. diff --git a/src/mscorlib/shared/System/Text/UTF7Encoding.cs b/src/mscorlib/shared/System/Text/UTF7Encoding.cs index b9065477e910..78813649b673 100644 --- a/src/mscorlib/shared/System/Text/UTF7Encoding.cs +++ b/src/mscorlib/shared/System/Text/UTF7Encoding.cs @@ -8,7 +8,6 @@ using System; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Text { @@ -140,7 +139,6 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // If no input, return 0, avoid fixed empty array problem if (count == 0) @@ -161,7 +159,6 @@ public override unsafe int GetByteCount(string s) // Validate input if (s==null) throw new ArgumentNullException("s"); - Contract.EndContractBlock(); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); @@ -180,7 +177,6 @@ public override unsafe int GetByteCount(char* chars, int count) if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Call it with empty encoder return GetByteCount(chars, count, null); @@ -205,7 +201,6 @@ public override unsafe int GetBytes(string s, int charIndex, int charCount, if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); int byteCount = bytes.Length - byteIndex; @@ -246,7 +241,6 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) @@ -277,7 +271,6 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return GetBytes(chars, charCount, bytes, byteCount, null); } @@ -301,7 +294,6 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count) if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // If no input just return 0, fixed doesn't like 0 length arrays. if (count == 0) @@ -325,7 +317,6 @@ public override unsafe int GetCharCount(byte* bytes, int count) if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return GetCharCount(bytes, count, null); } @@ -350,7 +341,6 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); // If no input, return 0 & avoid fixed problem if (byteCount == 0) @@ -381,7 +371,6 @@ public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return GetChars(bytes, byteCount, chars, charCount, null); } @@ -405,7 +394,6 @@ public override unsafe String GetString(byte[] bytes, int index, int count) if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // Avoid problems with empty input buffer if (count == 0) return String.Empty; @@ -762,7 +750,6 @@ public override int GetMaxByteCount(int charCount) if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Suppose that every char can not be direct-encoded, we know that // a byte can encode 6 bits of the Unicode character. And we will @@ -795,7 +782,6 @@ public override int GetMaxCharCount(int byteCount) if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Worst case is 1 char per byte. Minimum 1 for left over bits in case decoder is being flushed // Also note that we ignore extra bits (per spec), so UTF7 doesn't have unknown in this direction. diff --git a/src/mscorlib/shared/System/Text/UTF8Encoding.cs b/src/mscorlib/shared/System/Text/UTF8Encoding.cs index 974bf75650dd..e5544c519499 100644 --- a/src/mscorlib/shared/System/Text/UTF8Encoding.cs +++ b/src/mscorlib/shared/System/Text/UTF8Encoding.cs @@ -16,7 +16,6 @@ using System; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Globalization; namespace System.Text @@ -137,7 +136,6 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // If no input, return 0, avoid fixed empty array problem if (count == 0) @@ -158,7 +156,6 @@ public override unsafe int GetByteCount(String chars) // Validate input if (chars==null) throw new ArgumentNullException("s"); - Contract.EndContractBlock(); fixed (char* pChars = chars) return GetByteCount(pChars, chars.Length, null); @@ -177,7 +174,6 @@ public override unsafe int GetByteCount(char* chars, int count) if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Call it with empty encoder return GetByteCount(chars, count, null); @@ -202,7 +198,6 @@ public override unsafe int GetBytes(String s, int charIndex, int charCount, if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); int byteCount = bytes.Length - byteIndex; @@ -243,7 +238,6 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) @@ -274,7 +268,6 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return GetBytes(chars, charCount, bytes, byteCount, null); } @@ -298,7 +291,6 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count) if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // If no input just return 0, fixed doesn't like 0 length arrays. if (count == 0) @@ -322,7 +314,6 @@ public override unsafe int GetCharCount(byte* bytes, int count) if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return GetCharCount(bytes, count, null); } @@ -347,7 +338,6 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); // If no input, return 0 & avoid fixed problem if (byteCount == 0) @@ -378,7 +368,6 @@ public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return GetChars(bytes, byteCount, chars, charCount, null); } @@ -402,7 +391,6 @@ public override unsafe String GetString(byte[] bytes, int index, int count) if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // Avoid problems with empty input buffer if (count == 0) return String.Empty; @@ -2448,7 +2436,6 @@ public override int GetMaxByteCount(int charCount) if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback long byteCount = (long)charCount + 1; @@ -2471,7 +2458,6 @@ public override int GetMaxCharCount(int byteCount) if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Figure out our length, 1 char per input byte + 1 char if 1st byte is last byte of 4 byte surrogate pair long charCount = ((long)byteCount + 1); diff --git a/src/mscorlib/shared/System/Text/UnicodeEncoding.cs b/src/mscorlib/shared/System/Text/UnicodeEncoding.cs index 78355299c164..a5b89a66669e 100644 --- a/src/mscorlib/shared/System/Text/UnicodeEncoding.cs +++ b/src/mscorlib/shared/System/Text/UnicodeEncoding.cs @@ -9,7 +9,6 @@ using System; using System.Globalization; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Text { @@ -96,7 +95,6 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // If no input, return 0, avoid fixed empty array problem if (count == 0) @@ -117,7 +115,6 @@ public override unsafe int GetByteCount(String s) // Validate input if (s==null) throw new ArgumentNullException("s"); - Contract.EndContractBlock(); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); @@ -136,7 +133,6 @@ public override unsafe int GetByteCount(char* chars, int count) if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Call it with empty encoder return GetByteCount(chars, count, null); @@ -161,7 +157,6 @@ public override unsafe int GetBytes(String s, int charIndex, int charCount, if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); int byteCount = bytes.Length - byteIndex; @@ -202,7 +197,6 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) @@ -233,7 +227,6 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return GetBytes(chars, charCount, bytes, byteCount, null); } @@ -257,7 +250,6 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count) if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // If no input just return 0, fixed doesn't like 0 length arrays if (count == 0) @@ -281,7 +273,6 @@ public override unsafe int GetCharCount(byte* bytes, int count) if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return GetCharCount(bytes, count, null); } @@ -306,7 +297,6 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); // If no input, return 0 & avoid fixed problem if (byteCount == 0) @@ -337,7 +327,6 @@ public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); return GetChars(bytes, byteCount, chars, charCount, null); } @@ -361,7 +350,6 @@ public override unsafe string GetString(byte[] bytes, int index, int count) if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); // Avoid problems with empty input buffer if (count == 0) return String.Empty; @@ -1911,7 +1899,6 @@ public override int GetMaxByteCount(int charCount) if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback long byteCount = (long)charCount + 1; @@ -1934,7 +1921,6 @@ public override int GetMaxCharCount(int byteCount) if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // long because byteCount could be biggest int. // 1 char per 2 bytes. Round up in case 1 left over in decoder. diff --git a/src/mscorlib/shared/System/Threading/ExecutionContext.cs b/src/mscorlib/shared/System/Threading/ExecutionContext.cs index a573af33833a..2d5f5be19048 100644 --- a/src/mscorlib/shared/System/Threading/ExecutionContext.cs +++ b/src/mscorlib/shared/System/Threading/ExecutionContext.cs @@ -12,7 +12,6 @@ ===========================================================*/ using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.ExceptionServices; using System.Runtime.Serialization; @@ -103,7 +102,6 @@ public static AsyncFlowControl SuppressFlow() { throw new InvalidOperationException(SR.InvalidOperation_CannotSupressFlowMultipleTimes); } - Contract.EndContractBlock(); executionContext = executionContext.ShallowClone(isFlowSuppressed: true); var asyncFlowControl = new AsyncFlowControl(); @@ -120,7 +118,6 @@ public static void RestoreFlow() { throw new InvalidOperationException(SR.InvalidOperation_CannotRestoreUnsupressedFlow); } - Contract.EndContractBlock(); currentThread.ExecutionContext = executionContext.ShallowClone(isFlowSuppressed: false); } @@ -322,7 +319,6 @@ public void Undo() { throw new InvalidOperationException(SR.InvalidOperation_AsyncFlowCtrlCtxMismatch); } - Contract.EndContractBlock(); _thread = null; ExecutionContext.RestoreFlow(); diff --git a/src/mscorlib/shared/System/TimeSpan.cs b/src/mscorlib/shared/System/TimeSpan.cs index 263a0a5824b8..639d24b248b9 100644 --- a/src/mscorlib/shared/System/TimeSpan.cs +++ b/src/mscorlib/shared/System/TimeSpan.cs @@ -6,7 +6,6 @@ using System; using System.Runtime; using System.Runtime.CompilerServices; -using System.Diagnostics.Contracts; using System.Globalization; namespace System @@ -207,7 +206,6 @@ public TimeSpan Duration() { if (Ticks == TimeSpan.MinValue.Ticks) throw new OverflowException(SR.Overflow_Duration); - Contract.EndContractBlock(); return new TimeSpan(_ticks >= 0 ? _ticks : -_ticks); } @@ -244,7 +242,6 @@ private static TimeSpan Interval(double value, int scale) { if (Double.IsNaN(value)) throw new ArgumentException(SR.Arg_CannotBeNaN); - Contract.EndContractBlock(); double tmp = value * scale; double millis = tmp + (value >= 0 ? 0.5 : -0.5); if ((millis > Int64.MaxValue / TicksPerMillisecond) || (millis < Int64.MinValue / TicksPerMillisecond)) @@ -266,7 +263,6 @@ public TimeSpan Negate() { if (Ticks == TimeSpan.MinValue.Ticks) throw new OverflowException(SR.Overflow_NegateTwosCompNum); - Contract.EndContractBlock(); return new TimeSpan(-_ticks); } diff --git a/src/mscorlib/shared/System/UInt16.cs b/src/mscorlib/shared/System/UInt16.cs index 4cd290bc45c7..be61313e30bd 100644 --- a/src/mscorlib/shared/System/UInt16.cs +++ b/src/mscorlib/shared/System/UInt16.cs @@ -11,7 +11,6 @@ ** ===========================================================*/ -using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -79,26 +78,22 @@ public override int GetHashCode() // Converts the current value to a String in base-10 with no extra padding. public override String ToString() { - Contract.Ensures(Contract.Result() != null); return Number.FormatUInt32(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatUInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { - Contract.Ensures(Contract.Result() != null); return Number.FormatUInt32(m_value, format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatUInt32(m_value, format, NumberFormatInfo.GetInstance(provider)); } diff --git a/src/mscorlib/shared/System/UInt32.cs b/src/mscorlib/shared/System/UInt32.cs index 49835613b2bd..3cd016cba126 100644 --- a/src/mscorlib/shared/System/UInt32.cs +++ b/src/mscorlib/shared/System/UInt32.cs @@ -12,7 +12,6 @@ ** ===========================================================*/ -using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -89,25 +88,21 @@ public override int GetHashCode() // The base 10 representation of the number with no extra padding. public override String ToString() { - Contract.Ensures(Contract.Result() != null); return Number.FormatUInt32(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatUInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { - Contract.Ensures(Contract.Result() != null); return Number.FormatUInt32(m_value, format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatUInt32(m_value, format, NumberFormatInfo.GetInstance(provider)); } diff --git a/src/mscorlib/shared/System/UInt64.cs b/src/mscorlib/shared/System/UInt64.cs index 424d48b8b122..175d76330865 100644 --- a/src/mscorlib/shared/System/UInt64.cs +++ b/src/mscorlib/shared/System/UInt64.cs @@ -11,7 +11,6 @@ ** ===========================================================*/ -using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -86,25 +85,21 @@ public override int GetHashCode() public override String ToString() { - Contract.Ensures(Contract.Result() != null); return Number.FormatUInt64(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatUInt64(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { - Contract.Ensures(Contract.Result() != null); return Number.FormatUInt64(m_value, format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatUInt64(m_value, format, NumberFormatInfo.GetInstance(provider)); } diff --git a/src/mscorlib/shared/System/ValueTuple.cs b/src/mscorlib/shared/System/ValueTuple.cs index 3464f2781c99..d3ae20f41627 100644 --- a/src/mscorlib/shared/System/ValueTuple.cs +++ b/src/mscorlib/shared/System/ValueTuple.cs @@ -4,7 +4,7 @@ using System.Collections; using System.Collections.Generic; -using System.Diagnostics.Contracts; +using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using HashHelpers = System.Numerics.Hashing.HashHelpers; @@ -2186,7 +2186,7 @@ public override int GetHashCode() rest.GetHashCode()); } - Contract.Assert(false, "Missed all cases for computing ValueTuple hash code"); + Debug.Fail("Missed all cases for computing ValueTuple hash code"); return -1; } @@ -2237,7 +2237,7 @@ private int GetHashCodeCore(IEqualityComparer comparer) comparer.GetHashCode(Item7), rest.GetHashCode(comparer)); } - Contract.Assert(false, "Missed all cases for computing ValueTuple hash code"); + Debug.Fail("Missed all cases for computing ValueTuple hash code"); return -1; } diff --git a/src/mscorlib/shared/System/Version.cs b/src/mscorlib/shared/System/Version.cs index 9c66d9b904ef..a084f9f5a484 100644 --- a/src/mscorlib/shared/System/Version.cs +++ b/src/mscorlib/shared/System/Version.cs @@ -4,7 +4,6 @@ using System.Globalization; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Text; namespace System @@ -39,7 +38,6 @@ public Version(int major, int minor, int build, int revision) if (revision < 0) throw new ArgumentOutOfRangeException(nameof(revision), SR.ArgumentOutOfRange_Version); - Contract.EndContractBlock(); _Major = major; _Minor = minor; @@ -58,7 +56,6 @@ public Version(int major, int minor, int build) if (build < 0) throw new ArgumentOutOfRangeException(nameof(build), SR.ArgumentOutOfRange_Version); - Contract.EndContractBlock(); _Major = major; _Minor = minor; @@ -72,7 +69,6 @@ public Version(int major, int minor) if (minor < 0) throw new ArgumentOutOfRangeException(nameof(minor), SR.ArgumentOutOfRange_Version); - Contract.EndContractBlock(); _Major = major; _Minor = minor; @@ -441,7 +437,6 @@ private static bool TryParseComponent(ReadOnlySpan component, string compo { if ((Object)v1 == null) throw new ArgumentNullException(nameof(v1)); - Contract.EndContractBlock(); return (v1.CompareTo(v2) < 0); } @@ -449,7 +444,6 @@ private static bool TryParseComponent(ReadOnlySpan component, string compo { if ((Object)v1 == null) throw new ArgumentNullException(nameof(v1)); - Contract.EndContractBlock(); return (v1.CompareTo(v2) <= 0); } diff --git a/src/mscorlib/src/Internal/Padding.cs b/src/mscorlib/src/Internal/Padding.cs index d25acdc9c7a8..14bf998babaa 100644 --- a/src/mscorlib/src/Internal/Padding.cs +++ b/src/mscorlib/src/Internal/Padding.cs @@ -6,7 +6,6 @@ namespace Internal { - /// A class for common padding constants and eventually routines. internal static class PaddingHelpers { diff --git a/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs b/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs index 6365d0f7fd84..1b2b69519f2b 100644 --- a/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs +++ b/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs @@ -4,7 +4,6 @@ using System; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; diff --git a/src/mscorlib/src/Microsoft/Win32/OAVariantLib.cs b/src/mscorlib/src/Microsoft/Win32/OAVariantLib.cs index 93138e6e16f5..52224637b042 100644 --- a/src/mscorlib/src/Microsoft/Win32/OAVariantLib.cs +++ b/src/mscorlib/src/Microsoft/Win32/OAVariantLib.cs @@ -16,7 +16,7 @@ namespace Microsoft.Win32 { using System; - using System.Diagnostics.Contracts; + using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; @@ -99,7 +99,7 @@ internal static Variant ChangeType(Variant source, Type targetClass, short optio private static int GetCVTypeFromClass(Type ctype) { - Contract.Requires(ctype != null); + Debug.Assert(ctype != null); #if _DEBUG BCLDebug.Assert(ClassTypes[CV_OBJECT] == typeof(Object), "OAVariantLib::ClassTypes[CV_OBJECT] == Object.class"); #endif diff --git a/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs b/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs index 0a2057ca531d..e314c4816792 100644 --- a/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs +++ b/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs @@ -52,7 +52,7 @@ There might possibly be an interaction with yet a third registry key as well. using System; using System.Buffers; using System.Collections.Generic; -using System.Diagnostics.Contracts; +using System.Diagnostics; using System.IO; using System.Text; @@ -1011,7 +1011,7 @@ internal static String FixupName(String name) private static void FixupPath(StringBuilder path) { - Contract.Requires(path != null); + Debug.Assert(path != null); int length = path.Length; bool fixup = false; char markerChar = (char)0xFFFF; @@ -1107,7 +1107,6 @@ private RegistryKeyPermissionCheck GetSubKeyPermissonCheck(bool subkeyWritable) static private void ValidateKeyName(string name) { - Contract.Ensures(name != null); if (name == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.name); diff --git a/src/mscorlib/src/System/Activator.cs b/src/mscorlib/src/System/Activator.cs index be938aa43d2d..3fa92c587461 100644 --- a/src/mscorlib/src/System/Activator.cs +++ b/src/mscorlib/src/System/Activator.cs @@ -23,7 +23,6 @@ namespace System using System.Runtime.CompilerServices; using AssemblyHashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm; using System.Runtime.Versioning; - using System.Diagnostics.Contracts; // Only statics, does not need to be marked with the serializable attribute public sealed class Activator @@ -60,7 +59,6 @@ static public Object CreateInstance(Type type, { if ((object)type == null) throw new ArgumentNullException(nameof(type)); - Contract.EndContractBlock(); if (type is System.Reflection.Emit.TypeBuilder) throw new NotSupportedException(SR.NotSupported_CreateInstanceWithTypeBuilder); @@ -118,7 +116,6 @@ static internal Object CreateInstance(Type type, bool nonPublic, bool wrapExcept { if ((object)type == null) throw new ArgumentNullException(nameof(type)); - Contract.EndContractBlock(); RuntimeType rt = type.UnderlyingSystemType as RuntimeType; diff --git a/src/mscorlib/src/System/AppDomain.cs b/src/mscorlib/src/System/AppDomain.cs index 9df649cf530d..5f7c7205b639 100644 --- a/src/mscorlib/src/System/AppDomain.cs +++ b/src/mscorlib/src/System/AppDomain.cs @@ -321,7 +321,6 @@ public static AppDomain CurrentDomain { get { - Contract.Ensures(Contract.Result() != null); return Thread.GetDomain(); } } @@ -372,7 +371,6 @@ public void SetData(string name, object data) { if (name == null) throw new ArgumentNullException(nameof(name)); - Contract.EndContractBlock(); lock (((ICollection)LocalStore).SyncRoot) { @@ -385,7 +383,6 @@ public Object GetData(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); - Contract.EndContractBlock(); object data; lock (((ICollection)LocalStore).SyncRoot) @@ -632,7 +629,7 @@ private Dictionary LocalStore private void SetupFusionStore(AppDomainSetup info, AppDomainSetup oldInfo) { - Contract.Requires(info != null); + Debug.Assert(info != null); if (info.ApplicationBase == null) { @@ -694,9 +691,6 @@ private static object PrepareDataForSetup(String friendlyName, private static Object Setup(Object arg) { - Contract.Requires(arg != null && arg is Object[]); - Contract.Requires(((Object[])arg).Length >= 8); - Object[] args = (Object[])arg; String friendlyName = (String)args[0]; AppDomainSetup setup = (AppDomainSetup)args[1]; diff --git a/src/mscorlib/src/System/AppDomainSetup.cs b/src/mscorlib/src/System/AppDomainSetup.cs index d0fdf4e72512..f3b3d8c8236d 100644 --- a/src/mscorlib/src/System/AppDomainSetup.cs +++ b/src/mscorlib/src/System/AppDomainSetup.cs @@ -17,7 +17,6 @@ namespace System using System.Security; using Path = System.IO.Path; using System.Diagnostics; - using System.Diagnostics.Contracts; using System.Collections.Generic; internal sealed class AppDomainSetup @@ -128,7 +127,6 @@ internal string[] Value public String ApplicationBase { - [Pure] get { return Value[(int)LoaderInformation.ApplicationBaseValue]; diff --git a/src/mscorlib/src/System/ArgIterator.cs b/src/mscorlib/src/System/ArgIterator.cs index 584f85fbd363..51e416c7b02f 100644 --- a/src/mscorlib/src/System/ArgIterator.cs +++ b/src/mscorlib/src/System/ArgIterator.cs @@ -8,7 +8,6 @@ namespace System using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Versioning; - using System.Diagnostics.Contracts; // This class will not be marked serializable // Note: This type must have the same layout as the CLR's VARARGS type in CLRVarArgs.h. diff --git a/src/mscorlib/src/System/Array.cs b/src/mscorlib/src/System/Array.cs index 75e7679954bc..0841d7ac63b4 100644 --- a/src/mscorlib/src/System/Array.cs +++ b/src/mscorlib/src/System/Array.cs @@ -13,13 +13,12 @@ using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Security; -using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System { @@ -39,7 +38,6 @@ public static ReadOnlyCollection AsReadOnly(T[] array) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - Contract.Ensures(Contract.Result>() != null); // T[] implements IList. return new ReadOnlyCollection(array); @@ -49,9 +47,6 @@ public static void Resize(ref T[] array, int newSize) { if (newSize < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.newSize, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); - Contract.Ensures(Contract.ValueAtReturn(out array) != null); - Contract.Ensures(Contract.ValueAtReturn(out array).Length == newSize); - Contract.EndContractBlock(); T[] larray = array; if (larray == null) @@ -75,10 +70,6 @@ public unsafe static Array CreateInstance(Type elementType, int length) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType); if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(Contract.Result().Length == length); - Contract.Ensures(Contract.Result().Rank == 1); - Contract.EndContractBlock(); RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; if (t == null) @@ -94,10 +85,6 @@ public unsafe static Array CreateInstance(Type elementType, int length1, int len ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length1, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); if (length2 < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length2, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(Contract.Result().Rank == 2); - Contract.Ensures(Contract.Result().GetLength(0) == length1); - Contract.Ensures(Contract.Result().GetLength(1) == length2); RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; if (t == null) @@ -118,11 +105,6 @@ public unsafe static Array CreateInstance(Type elementType, int length1, int len ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length2, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); if (length3 < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length3, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(Contract.Result().Rank == 3); - Contract.Ensures(Contract.Result().GetLength(0) == length1); - Contract.Ensures(Contract.Result().GetLength(1) == length2); - Contract.Ensures(Contract.Result().GetLength(2) == length3); RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; if (t == null) @@ -142,9 +124,6 @@ public unsafe static Array CreateInstance(Type elementType, params int[] lengths ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths); if (lengths.Length == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank); - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(Contract.Result().Rank == lengths.Length); - Contract.EndContractBlock(); RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; if (t == null) @@ -170,9 +149,6 @@ public static Array CreateInstance(Type elementType, params long[] lengths) } if (lengths.Length == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank); - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(Contract.Result().Rank == lengths.Length); - Contract.EndContractBlock(); int[] intLengths = new int[lengths.Length]; @@ -200,9 +176,6 @@ public unsafe static Array CreateInstance(Type elementType, int[] lengths, int[] ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RanksAndBounds); if (lengths.Length == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank); - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(Contract.Result().Rank == lengths.Length); - Contract.EndContractBlock(); RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; if (t == null) @@ -238,13 +211,6 @@ public static void Copy(Array sourceArray, Array destinationArray, int length) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.sourceArray); if (destinationArray == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destinationArray); - /* - Contract.Requires(sourceArray.Rank == destinationArray.Rank); - Contract.Requires(length >= 0); - Contract.Requires(length <= sourceArray.GetLowerBound(0) + sourceArray.Length); - Contract.Requires(length <= destinationArray.GetLowerBound(0) + destinationArray.Length); - */ - Contract.EndContractBlock(); Copy(sourceArray, sourceArray.GetLowerBound(0), destinationArray, destinationArray.GetLowerBound(0), length, false); } @@ -308,7 +274,6 @@ public unsafe Object GetValue(params int[] indices) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); if (Rank != indices.Length) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); - Contract.EndContractBlock(); TypedReference elemref = new TypedReference(); fixed (int* pIndices = &indices[0]) @@ -320,7 +285,6 @@ public unsafe Object GetValue(int index) { if (Rank != 1) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need1DArray); - Contract.EndContractBlock(); TypedReference elemref = new TypedReference(); InternalGetReference(&elemref, 1, &index); @@ -331,7 +295,6 @@ public unsafe Object GetValue(int index1, int index2) { if (Rank != 2) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need2DArray); - Contract.EndContractBlock(); int* pIndices = stackalloc int[2]; pIndices[0] = index1; @@ -346,7 +309,6 @@ public unsafe Object GetValue(int index1, int index2, int index3) { if (Rank != 3) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need3DArray); - Contract.EndContractBlock(); int* pIndices = stackalloc int[3]; pIndices[0] = index1; @@ -362,7 +324,6 @@ public Object GetValue(long index) { if (index > Int32.MaxValue || index < Int32.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); - Contract.EndContractBlock(); return this.GetValue((int)index); } @@ -373,7 +334,6 @@ public Object GetValue(long index1, long index2) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index1, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); if (index2 > Int32.MaxValue || index2 < Int32.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); - Contract.EndContractBlock(); return this.GetValue((int)index1, (int)index2); } @@ -386,7 +346,6 @@ public Object GetValue(long index1, long index2, long index3) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); if (index3 > Int32.MaxValue || index3 < Int32.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index3, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); - Contract.EndContractBlock(); return this.GetValue((int)index1, (int)index2, (int)index3); } @@ -397,7 +356,6 @@ public Object GetValue(params long[] indices) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); if (Rank != indices.Length) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); - Contract.EndContractBlock(); int[] intIndices = new int[indices.Length]; @@ -417,7 +375,6 @@ public unsafe void SetValue(Object value, int index) { if (Rank != 1) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need1DArray); - Contract.EndContractBlock(); TypedReference elemref = new TypedReference(); InternalGetReference(&elemref, 1, &index); @@ -428,7 +385,6 @@ public unsafe void SetValue(Object value, int index1, int index2) { if (Rank != 2) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need2DArray); - Contract.EndContractBlock(); int* pIndices = stackalloc int[2]; pIndices[0] = index1; @@ -443,7 +399,6 @@ public unsafe void SetValue(Object value, int index1, int index2, int index3) { if (Rank != 3) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need3DArray); - Contract.EndContractBlock(); int* pIndices = stackalloc int[3]; pIndices[0] = index1; @@ -461,7 +416,6 @@ public unsafe void SetValue(Object value, params int[] indices) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); if (Rank != indices.Length) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); - Contract.EndContractBlock(); TypedReference elemref = new TypedReference(); fixed (int* pIndices = &indices[0]) @@ -473,7 +427,6 @@ public void SetValue(Object value, long index) { if (index > Int32.MaxValue || index < Int32.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); - Contract.EndContractBlock(); this.SetValue(value, (int)index); } @@ -484,7 +437,6 @@ public void SetValue(Object value, long index1, long index2) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index1, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); if (index2 > Int32.MaxValue || index2 < Int32.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); - Contract.EndContractBlock(); this.SetValue(value, (int)index1, (int)index2); } @@ -497,7 +449,6 @@ public void SetValue(Object value, long index1, long index2, long index3) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); if (index3 > Int32.MaxValue || index3 < Int32.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index3, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); - Contract.EndContractBlock(); this.SetValue(value, (int)index1, (int)index2, (int)index3); } @@ -508,7 +459,6 @@ public void SetValue(Object value, params long[] indices) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); if (Rank != indices.Length) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); - Contract.EndContractBlock(); int[] intIndices = new int[indices.Length]; @@ -534,7 +484,6 @@ public void SetValue(Object value, params long[] indices) public extern int Length { - [Pure] [MethodImpl(MethodImplOptions.InternalCall)] get; } @@ -542,7 +491,7 @@ public extern int Length private static int GetMedian(int low, int hi) { // Note both may be negative, if we are dealing with arrays w/ negative lower bounds. - Contract.Requires(low <= hi); + Debug.Assert(low <= hi); Debug.Assert(hi - low >= 0, "Length overflow!"); return low + ((hi - low) >> 1); } @@ -557,16 +506,13 @@ private static int GetMedian(int low, int hi) public extern long LongLength { - [Pure] [MethodImpl(MethodImplOptions.InternalCall)] get; } - [Pure] [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int GetLength(int dimension); - [Pure] public long GetLongLength(int dimension) { //This method should throw an IndexOufOfRangeException for compat if dimension < 0 or >= Rank @@ -575,16 +521,13 @@ public long GetLongLength(int dimension) public extern int Rank { - [Pure] [MethodImplAttribute(MethodImplOptions.InternalCall)] get; } - [Pure] [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int GetUpperBound(int dimension); - [Pure] [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int GetLowerBound(int dimension); @@ -741,7 +684,6 @@ int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { if (comparer == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparer); - Contract.EndContractBlock(); int ret = 0; @@ -766,13 +708,10 @@ int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) // negative result to produce the index of the first element (if any) that // is larger than the given search value. // - [Pure] public static int BinarySearch(Array array, Object value) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Contract.Ensures((Contract.Result() >= array.GetLowerBound(0) && Contract.Result() <= array.GetUpperBound(0)) || (Contract.Result() < array.GetLowerBound(0) && ~Contract.Result() <= array.GetUpperBound(0) + 1)); - Contract.EndContractBlock(); int lb = array.GetLowerBound(0); return BinarySearch(array, lb, array.Length, value, null); } @@ -790,7 +729,6 @@ public static int BinarySearch(Array array, Object value) // negative result to produce the index of the first element (if any) that // is larger than the given search value. // - [Pure] public static int BinarySearch(Array array, int index, int length, Object value) { return BinarySearch(array, index, length, value, null); @@ -810,12 +748,10 @@ public static int BinarySearch(Array array, int index, int length, Object value) // negative result to produce the index of the first element (if any) that // is larger than the given search value. // - [Pure] public static int BinarySearch(Array array, Object value, IComparer comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Contract.EndContractBlock(); int lb = array.GetLowerBound(0); return BinarySearch(array, lb, array.Length, value, comparer); } @@ -835,12 +771,10 @@ public static int BinarySearch(Array array, Object value, IComparer comparer) // negative result to produce the index of the first element (if any) that // is larger than the given search value. // - [Pure] public static int BinarySearch(Array array, int index, int length, Object value, IComparer comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Contract.EndContractBlock(); int lb = array.GetLowerBound(0); if (index < lb) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); @@ -922,31 +856,25 @@ public static int BinarySearch(Array array, int index, int length, Object value, [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool TrySZBinarySearch(Array sourceArray, int sourceIndex, int count, Object value, out int retVal); - [Pure] public static int BinarySearch(T[] array, T value) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Contract.EndContractBlock(); return BinarySearch(array, 0, array.Length, value, null); } - [Pure] public static int BinarySearch(T[] array, T value, System.Collections.Generic.IComparer comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Contract.EndContractBlock(); return BinarySearch(array, 0, array.Length, value, comparer); } - [Pure] public static int BinarySearch(T[] array, int index, int length, T value) { return BinarySearch(array, index, length, value, null); } - [Pure] public static int BinarySearch(T[] array, int index, int length, T value, System.Collections.Generic.IComparer comparer) { if (array == null) @@ -958,7 +886,6 @@ public static int BinarySearch(T[] array, int index, int length, T value, Sys if (array.Length - index < length) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); - Contract.EndContractBlock(); return ArraySortHelper.Default.BinarySearch(array, index, length, value, comparer); } @@ -974,9 +901,6 @@ public static TOutput[] ConvertAll(TInput[] array, Converter() != null); - Contract.Ensures(Contract.Result().Length == array.Length); - Contract.EndContractBlock(); TOutput[] newArray = new TOutput[array.Length]; for (int i = 0; i < array.Length; i++) @@ -993,22 +917,18 @@ public static TOutput[] ConvertAll(TInput[] array, Converter Int32.MaxValue || index < Int32.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); - Contract.EndContractBlock(); this.CopyTo(array, (int)index); } @@ -1018,13 +938,8 @@ private static class EmptyArray internal static readonly T[] Value = new T[0]; } - [Pure] public static T[] Empty() { - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(Contract.Result().Length == 0); - Contract.EndContractBlock(); - return EmptyArray.Value; } @@ -1080,7 +995,6 @@ public static T Find(T[] array, Predicate match) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - Contract.EndContractBlock(); for (int i = 0; i < array.Length; i++) { @@ -1103,7 +1017,6 @@ public static T[] FindAll(T[] array, Predicate match) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - Contract.EndContractBlock(); List list = new List(); for (int i = 0; i < array.Length; i++) @@ -1122,8 +1035,6 @@ public static int FindIndex(T[] array, Predicate match) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - Contract.Ensures(Contract.Result() < array.Length); - Contract.EndContractBlock(); return FindIndex(array, 0, array.Length, match); } @@ -1134,8 +1045,6 @@ public static int FindIndex(T[] array, int startIndex, Predicate match) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - Contract.Ensures(Contract.Result() < array.Length); - Contract.EndContractBlock(); return FindIndex(array, startIndex, array.Length - startIndex, match); } @@ -1161,8 +1070,6 @@ public static int FindIndex(T[] array, int startIndex, int count, Predicate() < array.Length); - Contract.EndContractBlock(); int endIndex = startIndex + count; for (int i = startIndex; i < endIndex; i++) @@ -1183,7 +1090,6 @@ public static T FindLast(T[] array, Predicate match) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - Contract.EndContractBlock(); for (int i = array.Length - 1; i >= 0; i--) { @@ -1201,7 +1107,6 @@ public static int FindLastIndex(T[] array, Predicate match) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - Contract.EndContractBlock(); return FindLastIndex(array, array.Length - 1, array.Length, match); } @@ -1212,7 +1117,6 @@ public static int FindLastIndex(T[] array, int startIndex, Predicate match { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - Contract.EndContractBlock(); return FindLastIndex(array, startIndex, startIndex + 1, match); } @@ -1228,7 +1132,6 @@ public static int FindLastIndex(T[] array, int startIndex, int count, Predica { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - Contract.EndContractBlock(); if (array.Length == 0) { @@ -1275,7 +1178,6 @@ public static void ForEach(T[] array, Action action) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action); } - Contract.EndContractBlock(); for (int i = 0; i < array.Length; i++) { @@ -1304,8 +1206,6 @@ public static int IndexOf(Array array, Object value) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Contract.Ensures(Contract.Result() < array.GetLowerBound(0) + array.Length); - Contract.EndContractBlock(); int lb = array.GetLowerBound(0); return IndexOf(array, value, lb, array.Length); } @@ -1320,8 +1220,6 @@ public static int IndexOf(Array array, Object value, int startIndex) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Contract.Ensures(Contract.Result() < array.GetLowerBound(0) + array.Length); - Contract.EndContractBlock(); int lb = array.GetLowerBound(0); return IndexOf(array, value, startIndex, array.Length - startIndex + lb); } @@ -1338,8 +1236,6 @@ public static int IndexOf(Array array, Object value, int startIndex, int count) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (array.Rank != 1) ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); - Contract.Ensures(Contract.Result() < array.GetLowerBound(0) + array.Length); - Contract.EndContractBlock(); int lb = array.GetLowerBound(0); if (startIndex < lb || startIndex > array.Length + lb) @@ -1395,16 +1291,12 @@ public static int IndexOf(Array array, Object value, int startIndex, int count) return lb - 1; } - [Pure] public static int IndexOf(T[] array, T value) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - Contract.Ensures((Contract.Result() < 0) || - (Contract.Result() >= 0 && Contract.Result() < array.Length && EqualityComparer.Default.Equals(value, array[Contract.Result()]))); - Contract.EndContractBlock(); return IndexOf(array, value, 0, array.Length); } @@ -1415,8 +1307,6 @@ public static int IndexOf(T[] array, T value, int startIndex) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - Contract.Ensures(Contract.Result() < array.Length); - Contract.EndContractBlock(); return IndexOf(array, value, startIndex, array.Length - startIndex); } @@ -1437,8 +1327,6 @@ public static int IndexOf(T[] array, T value, int startIndex, int count) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } - Contract.Ensures(Contract.Result() < array.Length); - Contract.EndContractBlock(); return EqualityComparer.Default.IndexOf(array, value, startIndex, count); } @@ -1455,8 +1343,6 @@ public static int LastIndexOf(Array array, Object value) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Contract.Ensures(Contract.Result() < array.GetLowerBound(0) + array.Length); - Contract.EndContractBlock(); int lb = array.GetLowerBound(0); return LastIndexOf(array, value, array.Length - 1 + lb, array.Length); } @@ -1470,8 +1356,6 @@ public static int LastIndexOf(Array array, Object value, int startIndex) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Contract.Ensures(Contract.Result() < array.GetLowerBound(0) + array.Length); - Contract.EndContractBlock(); int lb = array.GetLowerBound(0); return LastIndexOf(array, value, startIndex, startIndex + 1 - lb); } @@ -1486,8 +1370,6 @@ public static int LastIndexOf(Array array, Object value, int startIndex, int cou { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Contract.Ensures(Contract.Result() < array.GetLowerBound(0) + array.Length); - Contract.EndContractBlock(); int lb = array.GetLowerBound(0); if (array.Length == 0) { @@ -1553,8 +1435,6 @@ public static int LastIndexOf(T[] array, T value) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - Contract.Ensures(Contract.Result() < array.Length); - Contract.EndContractBlock(); return LastIndexOf(array, value, array.Length - 1, array.Length); } @@ -1565,8 +1445,6 @@ public static int LastIndexOf(T[] array, T value, int startIndex) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - Contract.Ensures(Contract.Result() < array.Length); - Contract.EndContractBlock(); // if array is empty and startIndex is 0, we need to pass 0 as count return LastIndexOf(array, value, startIndex, (array.Length == 0) ? 0 : (startIndex + 1)); } @@ -1577,8 +1455,6 @@ public static int LastIndexOf(T[] array, T value, int startIndex, int count) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - Contract.Ensures(Contract.Result() < array.Length); - Contract.EndContractBlock(); if (array.Length == 0) { @@ -1627,7 +1503,6 @@ public static void Reverse(Array array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Contract.EndContractBlock(); Reverse(array, array.GetLowerBound(0), array.Length); } @@ -1651,7 +1526,6 @@ public static void Reverse(Array array, int index, int length) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (array.Rank != 1) ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); - Contract.EndContractBlock(); bool r = TrySZReverse(array, index, length); if (r) @@ -1684,7 +1558,6 @@ public static void Reverse(T[] array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Contract.EndContractBlock(); Reverse(array, 0, array.Length); } @@ -1698,7 +1571,6 @@ public static void Reverse(T[] array, int index, int length) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); if (array.Length - index < length) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); - Contract.EndContractBlock(); ref T p = ref Unsafe.As(ref array.GetRawSzArrayData()); int i = index; @@ -1721,7 +1593,6 @@ public static void Sort(Array array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Contract.EndContractBlock(); Sort(array, null, array.GetLowerBound(0), array.Length, null); } @@ -1735,7 +1606,6 @@ public static void Sort(Array keys, Array items) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); - Contract.EndContractBlock(); Sort(keys, items, keys.GetLowerBound(0), keys.Length, null); } @@ -1769,7 +1639,6 @@ public static void Sort(Array array, IComparer comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Contract.EndContractBlock(); Sort(array, null, array.GetLowerBound(0), array.Length, comparer); } @@ -1785,7 +1654,6 @@ public static void Sort(Array keys, Array items, IComparer comparer) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); - Contract.EndContractBlock(); Sort(keys, items, keys.GetLowerBound(0), keys.Length, comparer); } @@ -1825,7 +1693,6 @@ public static void Sort(Array keys, Array items, int index, int length, ICompare if (keys.Length - (index - keysLowerBound) < length || (items != null && (index - keysLowerBound) > items.Length - length)) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); - Contract.EndContractBlock(); if (length > 1) { @@ -1860,7 +1727,6 @@ public static void Sort(T[] array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Contract.EndContractBlock(); Sort(array, 0, array.Length, null); } @@ -1868,7 +1734,6 @@ public static void Sort(TKey[] keys, TValue[] items) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); - Contract.EndContractBlock(); Sort(keys, items, 0, keys.Length, null); } @@ -1886,7 +1751,6 @@ public static void Sort(T[] array, System.Collections.Generic.IComparer co { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Contract.EndContractBlock(); Sort(array, 0, array.Length, comparer); } @@ -1894,7 +1758,6 @@ public static void Sort(TKey[] keys, TValue[] items, System.Collec { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); - Contract.EndContractBlock(); Sort(keys, items, 0, keys.Length, comparer); } @@ -1908,7 +1771,6 @@ public static void Sort(T[] array, int index, int length, System.Collections. ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); if (array.Length - index < length) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); - Contract.EndContractBlock(); if (length > 1) { @@ -1934,7 +1796,6 @@ public static void Sort(TKey[] keys, TValue[] items, int index, in ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); if (keys.Length - index < length || (items != null && index > items.Length - length)) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); - Contract.EndContractBlock(); if (length > 1) { @@ -1967,7 +1828,6 @@ public static void Sort(T[] array, Comparison comparison) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); } - Contract.EndContractBlock(); ArraySortHelper.Sort(array, 0, array.Length, comparison); } @@ -1983,7 +1843,6 @@ public static bool TrueForAll(T[] array, Predicate match) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - Contract.EndContractBlock(); for (int i = 0; i < array.Length; i++) { diff --git a/src/mscorlib/src/System/ArraySegment.cs b/src/mscorlib/src/System/ArraySegment.cs index 7546c5bd5666..a96db8f9f709 100644 --- a/src/mscorlib/src/System/ArraySegment.cs +++ b/src/mscorlib/src/System/ArraySegment.cs @@ -16,7 +16,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System { @@ -41,7 +40,6 @@ public ArraySegment(T[] array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Contract.EndContractBlock(); _array = array; _offset = 0; @@ -55,7 +53,6 @@ public ArraySegment(T[] array, int offset, int count) // Failure should be rare and location determination and message is delegated to failure functions if (array == null || (uint)offset > (uint)array.Length || (uint)count > (uint)(array.Length - offset)) ThrowHelper.ThrowArraySegmentCtorValidationFailedExceptions(array, offset, count); - Contract.EndContractBlock(); _array = array; _offset = offset; @@ -205,7 +202,6 @@ T IList.this[int index] ThrowInvalidOperationIfDefault(); if (index < 0 || index >= _count) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); - Contract.EndContractBlock(); return _array[_offset + index]; } @@ -215,7 +211,6 @@ T IList.this[int index] ThrowInvalidOperationIfDefault(); if (index < 0 || index >= _count) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); - Contract.EndContractBlock(); _array[_offset + index] = value; } @@ -252,7 +247,6 @@ T IReadOnlyList.this[int index] ThrowInvalidOperationIfDefault(); if (index < 0 || index >= _count) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); - Contract.EndContractBlock(); return _array[_offset + index]; } @@ -326,10 +320,10 @@ public struct Enumerator : IEnumerator internal Enumerator(ArraySegment arraySegment) { - Contract.Requires(arraySegment.Array != null); - Contract.Requires(arraySegment.Offset >= 0); - Contract.Requires(arraySegment.Count >= 0); - Contract.Requires(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length); + Debug.Assert(arraySegment.Array != null); + Debug.Assert(arraySegment.Offset >= 0); + Debug.Assert(arraySegment.Count >= 0); + Debug.Assert(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length); _array = arraySegment.Array; _start = arraySegment.Offset; diff --git a/src/mscorlib/src/System/Attribute.cs b/src/mscorlib/src/System/Attribute.cs index 23fd9aaaafde..37445cc23b63 100644 --- a/src/mscorlib/src/System/Attribute.cs +++ b/src/mscorlib/src/System/Attribute.cs @@ -10,7 +10,6 @@ using System.Runtime.InteropServices; using System.Globalization; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Security; namespace System @@ -25,9 +24,9 @@ public abstract class Attribute #region PropertyInfo private static Attribute[] InternalGetCustomAttributes(PropertyInfo element, Type type, bool inherit) { - Contract.Requires(element != null); - Contract.Requires(type != null); - Contract.Requires(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute)); + Debug.Assert(element != null); + Debug.Assert(type != null); + Debug.Assert(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute)); // walk up the hierarchy chain Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit); @@ -90,7 +89,7 @@ private static bool InternalIsDefined(PropertyInfo element, Type attributeType, private static PropertyInfo GetParentDefinition(PropertyInfo property, Type[] propertyParameters) { - Contract.Requires(property != null); + Debug.Assert(property != null); // for the current property get the base class of the getter and the setter, they might be different // note that this only works for RuntimeMethodInfo @@ -127,9 +126,9 @@ private static PropertyInfo GetParentDefinition(PropertyInfo property, Type[] pr #region EventInfo private static Attribute[] InternalGetCustomAttributes(EventInfo element, Type type, bool inherit) { - Contract.Requires(element != null); - Contract.Requires(type != null); - Contract.Requires(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute)); + Debug.Assert(element != null); + Debug.Assert(type != null); + Debug.Assert(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute)); // walk up the hierarchy chain Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit); @@ -158,7 +157,7 @@ private static Attribute[] InternalGetCustomAttributes(EventInfo element, Type t private static EventInfo GetParentDefinition(EventInfo ev) { - Contract.Requires(ev != null); + Debug.Assert(ev != null); // note that this only works for RuntimeMethodInfo MethodInfo add = ev.GetAddMethod(true); @@ -176,7 +175,7 @@ private static EventInfo GetParentDefinition(EventInfo ev) private static bool InternalIsDefined(EventInfo element, Type attributeType, bool inherit) { - Contract.Requires(element != null); + Debug.Assert(element != null); // walk up the hierarchy chain if (element.IsDefined(attributeType, inherit)) @@ -207,7 +206,7 @@ private static bool InternalIsDefined(EventInfo element, Type attributeType, boo #region ParameterInfo private static ParameterInfo GetParentDefinition(ParameterInfo param) { - Contract.Requires(param != null); + Debug.Assert(param != null); // note that this only works for RuntimeMethodInfo RuntimeMethodInfo rtMethod = param.Member as RuntimeMethodInfo; @@ -236,7 +235,7 @@ private static ParameterInfo GetParentDefinition(ParameterInfo param) private static Attribute[] InternalParamGetCustomAttributes(ParameterInfo param, Type type, bool inherit) { - Contract.Requires(param != null); + Debug.Assert(param != null); // For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain that // have this ParameterInfo defined. .We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes @@ -326,8 +325,8 @@ private static Attribute[] InternalParamGetCustomAttributes(ParameterInfo param, private static bool InternalParamIsDefined(ParameterInfo param, Type type, bool inherit) { - Contract.Requires(param != null); - Contract.Requires(type != null); + Debug.Assert(param != null); + Debug.Assert(type != null); // For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain. // We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes @@ -461,7 +460,6 @@ public static Attribute[] GetCustomAttributes(MemberInfo element, Type type, boo if (!type.IsSubclassOf(typeof(Attribute)) && type != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); - Contract.EndContractBlock(); switch (element.MemberType) { @@ -485,7 +483,6 @@ public static Attribute[] GetCustomAttributes(MemberInfo element, bool inherit) { if (element == null) throw new ArgumentNullException(nameof(element)); - Contract.EndContractBlock(); switch (element.MemberType) { @@ -516,7 +513,6 @@ public static bool IsDefined(MemberInfo element, Type attributeType, bool inheri if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); - Contract.EndContractBlock(); switch (element.MemberType) { @@ -576,7 +572,6 @@ public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attrib if (element.Member == null) throw new ArgumentException(SR.Argument_InvalidParameterInfo, nameof(element)); - Contract.EndContractBlock(); MemberInfo member = element.Member; if (member.MemberType == MemberTypes.Method && inherit) @@ -593,7 +588,6 @@ public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inheri if (element.Member == null) throw new ArgumentException(SR.Argument_InvalidParameterInfo, nameof(element)); - Contract.EndContractBlock(); MemberInfo member = element.Member; if (member.MemberType == MemberTypes.Method && inherit) @@ -618,7 +612,6 @@ public static bool IsDefined(ParameterInfo element, Type attributeType, bool inh if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); - Contract.EndContractBlock(); MemberInfo member = element.Member; @@ -679,7 +672,6 @@ public static Attribute[] GetCustomAttributes(Module element, bool inherit) { if (element == null) throw new ArgumentNullException(nameof(element)); - Contract.EndContractBlock(); return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit); } @@ -694,7 +686,6 @@ public static Attribute[] GetCustomAttributes(Module element, Type attributeType if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); - Contract.EndContractBlock(); return (Attribute[])element.GetCustomAttributes(attributeType, inherit); } @@ -715,7 +706,6 @@ public static bool IsDefined(Module element, Type attributeType, bool inherit) if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); - Contract.EndContractBlock(); return element.IsDefined(attributeType, false); } @@ -758,7 +748,6 @@ public static Attribute[] GetCustomAttributes(Assembly element, Type attributeTy if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); - Contract.EndContractBlock(); return (Attribute[])element.GetCustomAttributes(attributeType, inherit); } @@ -772,7 +761,6 @@ public static Attribute[] GetCustomAttributes(Assembly element, bool inherit) { if (element == null) throw new ArgumentNullException(nameof(element)); - Contract.EndContractBlock(); return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit); } @@ -793,7 +781,6 @@ public static bool IsDefined(Assembly element, Type attributeType, bool inherit) if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); - Contract.EndContractBlock(); return element.IsDefined(attributeType, false); } diff --git a/src/mscorlib/src/System/BCLDebug.cs b/src/mscorlib/src/System/BCLDebug.cs index 4a5f6d1891cc..9170a55c38e7 100644 --- a/src/mscorlib/src/System/BCLDebug.cs +++ b/src/mscorlib/src/System/BCLDebug.cs @@ -20,7 +20,6 @@ namespace System using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; - using System.Diagnostics.Contracts; internal enum LogLevel { @@ -121,7 +120,6 @@ static public void Assert(bool condition, String message) #endif } - [Pure] [Conditional("_LOGGING")] static public void Log(String message) { @@ -135,7 +133,6 @@ static public void Log(String message) System.Diagnostics.Log.Trace(Environment.NewLine); } - [Pure] [Conditional("_LOGGING")] static public void Log(String switchName, String message) { @@ -254,7 +251,6 @@ private static bool CheckEnabled(String switchName, LogLevel level, out LogSwitc return ((int)logSwitch.MinimumLevel <= (int)level); } - [Pure] [Conditional("_LOGGING")] public static void Log(String switchName, LogLevel level, params Object[] messages) { @@ -298,7 +294,6 @@ public static void Log(String switchName, LogLevel level, params Object[] messag System.Diagnostics.Log.LogMessage((LoggingLevels)((int)level), logSwitch, StringBuilderCache.GetStringAndRelease(sb)); } - [Pure] [Conditional("_LOGGING")] public static void Trace(String switchName, String format, params Object[] messages) { diff --git a/src/mscorlib/src/System/Buffer.cs b/src/mscorlib/src/System/Buffer.cs index 71859ec58717..1a5a4b6ad95c 100644 --- a/src/mscorlib/src/System/Buffer.cs +++ b/src/mscorlib/src/System/Buffer.cs @@ -16,7 +16,6 @@ namespace System using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics; - using System.Diagnostics.Contracts; using System.Security; using System.Runtime; diff --git a/src/mscorlib/src/System/Collections/Comparer.cs b/src/mscorlib/src/System/Collections/Comparer.cs index 00259e6bdbd8..28baf90caeb5 100644 --- a/src/mscorlib/src/System/Collections/Comparer.cs +++ b/src/mscorlib/src/System/Collections/Comparer.cs @@ -14,7 +14,6 @@ ===========================================================*/ using System.Globalization; -using System.Diagnostics.Contracts; namespace System.Collections { @@ -35,7 +34,6 @@ public Comparer(CultureInfo culture) { throw new ArgumentNullException(nameof(culture)); } - Contract.EndContractBlock(); m_compareInfo = culture.CompareInfo; } diff --git a/src/mscorlib/src/System/Collections/CompatibleComparer.cs b/src/mscorlib/src/System/Collections/CompatibleComparer.cs index 7dcaa4e1033b..eb74123036ba 100644 --- a/src/mscorlib/src/System/Collections/CompatibleComparer.cs +++ b/src/mscorlib/src/System/Collections/CompatibleComparer.cs @@ -4,7 +4,6 @@ // -using System.Diagnostics.Contracts; namespace System.Collections { @@ -46,7 +45,6 @@ public int GetHashCode(Object obj) { throw new ArgumentNullException(nameof(obj)); } - Contract.EndContractBlock(); if (_hcp != null) return _hcp.GetHashCode(obj); diff --git a/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs b/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs index 9841bdb4bb5c..a6a04b4964cd 100644 --- a/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs +++ b/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs @@ -13,7 +13,6 @@ ** ===========================================================*/ -using System.Diagnostics.Contracts; namespace System.Collections { @@ -49,7 +48,6 @@ public void CopyTo(Array array, int index) if (array.Length - index < this.Count) throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index)); - Contract.EndContractBlock(); // the actual copy is a NOP } @@ -88,7 +86,6 @@ public Object this[Object key] { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } - Contract.EndContractBlock(); return null; } set @@ -103,7 +100,6 @@ public Object this[Object key] if ((value != null) && (!value.GetType().IsSerializable)) throw new ArgumentException(SR.Argument_NotSerializable, nameof(value)); - Contract.EndContractBlock(); throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } @@ -142,7 +138,6 @@ public void Add(Object key, Object value) if ((value != null) && (!value.GetType().IsSerializable)) throw new ArgumentException(SR.Argument_NotSerializable, nameof(value)); - Contract.EndContractBlock(); throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } diff --git a/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs b/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs index e4a4acf74e22..be9ffb0566cd 100644 --- a/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs +++ b/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs @@ -17,7 +17,6 @@ using System.Globalization; using System.Runtime.CompilerServices; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.Versioning; namespace System.Collections.Generic @@ -155,8 +154,8 @@ internal static void Sort(T[] keys, int index, int length, Comparison compare internal static int InternalBinarySearch(T[] array, int index, int length, T value, IComparer comparer) { - Contract.Requires(array != null, "Check the arguments in the caller!"); - Contract.Requires(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); + Debug.Assert(array != null, "Check the arguments in the caller!"); + Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); int lo = index; int hi = index + length - 1; @@ -204,12 +203,12 @@ private static void Swap(T[] a, int i, int j) internal static void IntrospectiveSort(T[] keys, int left, int length, Comparison comparer) { - Contract.Requires(keys != null); - Contract.Requires(comparer != null); - Contract.Requires(left >= 0); - Contract.Requires(length >= 0); - Contract.Requires(length <= keys.Length); - Contract.Requires(length + left <= keys.Length); + Debug.Assert(keys != null); + Debug.Assert(comparer != null); + Debug.Assert(left >= 0); + Debug.Assert(length >= 0); + Debug.Assert(length <= keys.Length); + Debug.Assert(length + left <= keys.Length); if (length < 2) return; @@ -219,10 +218,10 @@ internal static void IntrospectiveSort(T[] keys, int left, int length, Compariso private static void IntroSort(T[] keys, int lo, int hi, int depthLimit, Comparison comparer) { - Contract.Requires(keys != null); - Contract.Requires(comparer != null); - Contract.Requires(lo >= 0); - Contract.Requires(hi < keys.Length); + Debug.Assert(keys != null); + Debug.Assert(comparer != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi < keys.Length); while (hi > lo) { @@ -266,12 +265,11 @@ private static void IntroSort(T[] keys, int lo, int hi, int depthLimit, Comparis private static int PickPivotAndPartition(T[] keys, int lo, int hi, Comparison comparer) { - Contract.Requires(keys != null); - Contract.Requires(comparer != null); - Contract.Requires(lo >= 0); - Contract.Requires(hi > lo); - Contract.Requires(hi < keys.Length); - Contract.Ensures(Contract.Result() >= lo && Contract.Result() <= hi); + Debug.Assert(keys != null); + Debug.Assert(comparer != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi > lo); + Debug.Assert(hi < keys.Length); // Compute median-of-three. But also partition them, since we've done the comparison. int middle = lo + ((hi - lo) / 2); @@ -303,11 +301,11 @@ private static int PickPivotAndPartition(T[] keys, int lo, int hi, Comparison private static void Heapsort(T[] keys, int lo, int hi, Comparison comparer) { - Contract.Requires(keys != null); - Contract.Requires(comparer != null); - Contract.Requires(lo >= 0); - Contract.Requires(hi > lo); - Contract.Requires(hi < keys.Length); + Debug.Assert(keys != null); + Debug.Assert(comparer != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi > lo); + Debug.Assert(hi < keys.Length); int n = hi - lo + 1; for (int i = n / 2; i >= 1; i = i - 1) @@ -323,10 +321,10 @@ private static void Heapsort(T[] keys, int lo, int hi, Comparison comparer) private static void DownHeap(T[] keys, int i, int n, int lo, Comparison comparer) { - Contract.Requires(keys != null); - Contract.Requires(comparer != null); - Contract.Requires(lo >= 0); - Contract.Requires(lo < keys.Length); + Debug.Assert(keys != null); + Debug.Assert(comparer != null); + Debug.Assert(lo >= 0); + Debug.Assert(lo < keys.Length); T d = keys[lo + i - 1]; int child; @@ -347,10 +345,10 @@ private static void DownHeap(T[] keys, int i, int n, int lo, Comparison compa private static void InsertionSort(T[] keys, int lo, int hi, Comparison comparer) { - Contract.Requires(keys != null); - Contract.Requires(lo >= 0); - Contract.Requires(hi >= lo); - Contract.Requires(hi <= keys.Length); + Debug.Assert(keys != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi >= lo); + Debug.Assert(hi <= keys.Length); int i, j; T t; @@ -466,9 +464,9 @@ private static int BinarySearch(T[] array, int index, int length, T value) private static void SwapIfGreaterWithItems(T[] keys, int a, int b) { - Contract.Requires(keys != null); - Contract.Requires(0 <= a && a < keys.Length); - Contract.Requires(0 <= b && b < keys.Length); + Debug.Assert(keys != null); + Debug.Assert(0 <= a && a < keys.Length); + Debug.Assert(0 <= b && b < keys.Length); if (a != b) { @@ -493,11 +491,11 @@ private static void Swap(T[] a, int i, int j) internal static void IntrospectiveSort(T[] keys, int left, int length) { - Contract.Requires(keys != null); - Contract.Requires(left >= 0); - Contract.Requires(length >= 0); - Contract.Requires(length <= keys.Length); - Contract.Requires(length + left <= keys.Length); + Debug.Assert(keys != null); + Debug.Assert(left >= 0); + Debug.Assert(length >= 0); + Debug.Assert(length <= keys.Length); + Debug.Assert(length + left <= keys.Length); if (length < 2) return; @@ -507,9 +505,9 @@ internal static void IntrospectiveSort(T[] keys, int left, int length) private static void IntroSort(T[] keys, int lo, int hi, int depthLimit) { - Contract.Requires(keys != null); - Contract.Requires(lo >= 0); - Contract.Requires(hi < keys.Length); + Debug.Assert(keys != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi < keys.Length); while (hi > lo) { @@ -553,11 +551,10 @@ private static void IntroSort(T[] keys, int lo, int hi, int depthLimit) private static int PickPivotAndPartition(T[] keys, int lo, int hi) { - Contract.Requires(keys != null); - Contract.Requires(lo >= 0); - Contract.Requires(hi > lo); - Contract.Requires(hi < keys.Length); - Contract.Ensures(Contract.Result() >= lo && Contract.Result() <= hi); + Debug.Assert(keys != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi > lo); + Debug.Assert(hi < keys.Length); // Compute median-of-three. But also partition them, since we've done the comparison. int middle = lo + ((hi - lo) / 2); @@ -597,10 +594,10 @@ private static int PickPivotAndPartition(T[] keys, int lo, int hi) private static void Heapsort(T[] keys, int lo, int hi) { - Contract.Requires(keys != null); - Contract.Requires(lo >= 0); - Contract.Requires(hi > lo); - Contract.Requires(hi < keys.Length); + Debug.Assert(keys != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi > lo); + Debug.Assert(hi < keys.Length); int n = hi - lo + 1; for (int i = n / 2; i >= 1; i = i - 1) @@ -616,9 +613,9 @@ private static void Heapsort(T[] keys, int lo, int hi) private static void DownHeap(T[] keys, int i, int n, int lo) { - Contract.Requires(keys != null); - Contract.Requires(lo >= 0); - Contract.Requires(lo < keys.Length); + Debug.Assert(keys != null); + Debug.Assert(lo >= 0); + Debug.Assert(lo < keys.Length); T d = keys[lo + i - 1]; int child; @@ -639,10 +636,10 @@ private static void DownHeap(T[] keys, int i, int n, int lo) private static void InsertionSort(T[] keys, int lo, int hi) { - Contract.Requires(keys != null); - Contract.Requires(lo >= 0); - Contract.Requires(hi >= lo); - Contract.Requires(hi <= keys.Length); + Debug.Assert(keys != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi >= lo); + Debug.Assert(hi <= keys.Length); int i, j; T t; @@ -728,11 +725,11 @@ public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer< private static void SwapIfGreaterWithItems(TKey[] keys, TValue[] values, IComparer comparer, int a, int b) { - Contract.Requires(keys != null); - Contract.Requires(values == null || values.Length >= keys.Length); - Contract.Requires(comparer != null); - Contract.Requires(0 <= a && a < keys.Length); - Contract.Requires(0 <= b && b < keys.Length); + Debug.Assert(keys != null); + Debug.Assert(values == null || values.Length >= keys.Length); + Debug.Assert(comparer != null); + Debug.Assert(0 <= a && a < keys.Length); + Debug.Assert(0 <= b && b < keys.Length); if (a != b) { @@ -769,14 +766,14 @@ private static void Swap(TKey[] keys, TValue[] values, int i, int j) internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, int length, IComparer comparer) { - Contract.Requires(keys != null); - Contract.Requires(values != null); - Contract.Requires(comparer != null); - Contract.Requires(left >= 0); - Contract.Requires(length >= 0); - Contract.Requires(length <= keys.Length); - Contract.Requires(length + left <= keys.Length); - Contract.Requires(length + left <= values.Length); + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(comparer != null); + Debug.Assert(left >= 0); + Debug.Assert(length >= 0); + Debug.Assert(length <= keys.Length); + Debug.Assert(length + left <= keys.Length); + Debug.Assert(length + left <= values.Length); if (length < 2) return; @@ -786,11 +783,11 @@ internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, i private static void IntroSort(TKey[] keys, TValue[] values, int lo, int hi, int depthLimit, IComparer comparer) { - Contract.Requires(keys != null); - Contract.Requires(values != null); - Contract.Requires(comparer != null); - Contract.Requires(lo >= 0); - Contract.Requires(hi < keys.Length); + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(comparer != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi < keys.Length); while (hi > lo) { @@ -834,13 +831,12 @@ private static void IntroSort(TKey[] keys, TValue[] values, int lo, int hi, int private static int PickPivotAndPartition(TKey[] keys, TValue[] values, int lo, int hi, IComparer comparer) { - Contract.Requires(keys != null); - Contract.Requires(values != null); - Contract.Requires(comparer != null); - Contract.Requires(lo >= 0); - Contract.Requires(hi > lo); - Contract.Requires(hi < keys.Length); - Contract.Ensures(Contract.Result() >= lo && Contract.Result() <= hi); + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(comparer != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi > lo); + Debug.Assert(hi < keys.Length); // Compute median-of-three. But also partition them, since we've done the comparison. int middle = lo + ((hi - lo) / 2); @@ -872,12 +868,12 @@ private static int PickPivotAndPartition(TKey[] keys, TValue[] values, int lo, i private static void Heapsort(TKey[] keys, TValue[] values, int lo, int hi, IComparer comparer) { - Contract.Requires(keys != null); - Contract.Requires(values != null); - Contract.Requires(comparer != null); - Contract.Requires(lo >= 0); - Contract.Requires(hi > lo); - Contract.Requires(hi < keys.Length); + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(comparer != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi > lo); + Debug.Assert(hi < keys.Length); int n = hi - lo + 1; for (int i = n / 2; i >= 1; i = i - 1) @@ -893,10 +889,10 @@ private static void Heapsort(TKey[] keys, TValue[] values, int lo, int hi, IComp private static void DownHeap(TKey[] keys, TValue[] values, int i, int n, int lo, IComparer comparer) { - Contract.Requires(keys != null); - Contract.Requires(comparer != null); - Contract.Requires(lo >= 0); - Contract.Requires(lo < keys.Length); + Debug.Assert(keys != null); + Debug.Assert(comparer != null); + Debug.Assert(lo >= 0); + Debug.Assert(lo < keys.Length); TKey d = keys[lo + i - 1]; TValue dValue = (values != null) ? values[lo + i - 1] : default(TValue); @@ -922,12 +918,12 @@ private static void DownHeap(TKey[] keys, TValue[] values, int i, int n, int lo, private static void InsertionSort(TKey[] keys, TValue[] values, int lo, int hi, IComparer comparer) { - Contract.Requires(keys != null); - Contract.Requires(values != null); - Contract.Requires(comparer != null); - Contract.Requires(lo >= 0); - Contract.Requires(hi >= lo); - Contract.Requires(hi <= keys.Length); + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(comparer != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi >= lo); + Debug.Assert(hi <= keys.Length); int i, j; TKey t; @@ -1020,13 +1016,13 @@ private static void Swap(TKey[] keys, TValue[] values, int i, int j) internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, int length) { - Contract.Requires(keys != null); - Contract.Requires(values != null); - Contract.Requires(left >= 0); - Contract.Requires(length >= 0); - Contract.Requires(length <= keys.Length); - Contract.Requires(length + left <= keys.Length); - Contract.Requires(length + left <= values.Length); + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(left >= 0); + Debug.Assert(length >= 0); + Debug.Assert(length <= keys.Length); + Debug.Assert(length + left <= keys.Length); + Debug.Assert(length + left <= values.Length); if (length < 2) return; @@ -1036,10 +1032,10 @@ internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, i private static void IntroSort(TKey[] keys, TValue[] values, int lo, int hi, int depthLimit) { - Contract.Requires(keys != null); - Contract.Requires(values != null); - Contract.Requires(lo >= 0); - Contract.Requires(hi < keys.Length); + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi < keys.Length); while (hi > lo) { @@ -1083,12 +1079,11 @@ private static void IntroSort(TKey[] keys, TValue[] values, int lo, int hi, int private static int PickPivotAndPartition(TKey[] keys, TValue[] values, int lo, int hi) { - Contract.Requires(keys != null); - Contract.Requires(values != null); - Contract.Requires(lo >= 0); - Contract.Requires(hi > lo); - Contract.Requires(hi < keys.Length); - Contract.Ensures(Contract.Result() >= lo && Contract.Result() <= hi); + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi > lo); + Debug.Assert(hi < keys.Length); // Compute median-of-three. But also partition them, since we've done the comparison. int middle = lo + ((hi - lo) / 2); @@ -1128,11 +1123,11 @@ private static int PickPivotAndPartition(TKey[] keys, TValue[] values, int lo, i private static void Heapsort(TKey[] keys, TValue[] values, int lo, int hi) { - Contract.Requires(keys != null); - Contract.Requires(values != null); - Contract.Requires(lo >= 0); - Contract.Requires(hi > lo); - Contract.Requires(hi < keys.Length); + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi > lo); + Debug.Assert(hi < keys.Length); int n = hi - lo + 1; for (int i = n / 2; i >= 1; i = i - 1) @@ -1148,9 +1143,9 @@ private static void Heapsort(TKey[] keys, TValue[] values, int lo, int hi) private static void DownHeap(TKey[] keys, TValue[] values, int i, int n, int lo) { - Contract.Requires(keys != null); - Contract.Requires(lo >= 0); - Contract.Requires(lo < keys.Length); + Debug.Assert(keys != null); + Debug.Assert(lo >= 0); + Debug.Assert(lo < keys.Length); TKey d = keys[lo + i - 1]; TValue dValue = (values != null) ? values[lo + i - 1] : default(TValue); @@ -1176,11 +1171,11 @@ private static void DownHeap(TKey[] keys, TValue[] values, int i, int n, int lo) private static void InsertionSort(TKey[] keys, TValue[] values, int lo, int hi) { - Contract.Requires(keys != null); - Contract.Requires(values != null); - Contract.Requires(lo >= 0); - Contract.Requires(hi >= lo); - Contract.Requires(hi <= keys.Length); + Debug.Assert(keys != null); + Debug.Assert(values != null); + Debug.Assert(lo >= 0); + Debug.Assert(hi >= lo); + Debug.Assert(hi <= keys.Length); int i, j; TKey t; diff --git a/src/mscorlib/src/System/Collections/Generic/Comparer.cs b/src/mscorlib/src/System/Collections/Generic/Comparer.cs index 47c241500d06..bb9e07d4916c 100644 --- a/src/mscorlib/src/System/Collections/Generic/Comparer.cs +++ b/src/mscorlib/src/System/Collections/Generic/Comparer.cs @@ -8,7 +8,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; //using System.Globalization; using System.Runtime.CompilerServices; using System.Security; @@ -27,8 +26,6 @@ public abstract class Comparer : IComparer, IComparer public static Comparer Create(Comparison comparison) { - Contract.Ensures(Contract.Result>() != null); - if (comparison == null) throw new ArgumentNullException(nameof(comparison)); diff --git a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs index 1ba146679e5f..761f775905a7 100644 --- a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs +++ b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs @@ -24,7 +24,6 @@ namespace System.Collections.Generic using System; using System.Collections; using System.Diagnostics; - using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.Serialization; @@ -176,7 +175,6 @@ public KeyCollection Keys { get { - Contract.Ensures(Contract.Result() != null); if (keys == null) keys = new KeyCollection(this); return keys; } @@ -204,7 +202,6 @@ public ValueCollection Values { get { - Contract.Ensures(Contract.Result() != null); if (values == null) values = new ValueCollection(this); return values; } diff --git a/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs b/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs index 4427682d3864..2b2869ab4a6c 100644 --- a/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs +++ b/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs @@ -11,7 +11,6 @@ using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.Serialization; -using System.Diagnostics.Contracts; namespace System.Collections.Generic { @@ -24,9 +23,7 @@ public abstract class EqualityComparer : IEqualityComparer, IEqualityComparer // as possible and define most of the creation logic in a non-generic class. public static EqualityComparer Default { get; } = (EqualityComparer)ComparerHelpers.CreateDefaultEqualityComparer(typeof(T)); - [Pure] public abstract bool Equals(T x, T y); - [Pure] public abstract int GetHashCode(T obj); internal virtual int IndexOf(T[] array, T value, int startIndex, int count) @@ -73,7 +70,6 @@ bool IEqualityComparer.Equals(object x, object y) [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] internal class GenericEqualityComparer : EqualityComparer where T : IEquatable { - [Pure] public override bool Equals(T x, T y) { if (x != null) @@ -85,7 +81,6 @@ public override bool Equals(T x, T y) return true; } - [Pure] public override int GetHashCode(T obj) => obj?.GetHashCode() ?? 0; internal override int IndexOf(T[] array, T value, int startIndex, int count) @@ -142,7 +137,6 @@ public override int GetHashCode() => [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] internal sealed class NullableEqualityComparer : EqualityComparer where T : struct, IEquatable { - [Pure] public override bool Equals(T? x, T? y) { if (x.HasValue) @@ -154,7 +148,6 @@ public override bool Equals(T? x, T? y) return true; } - [Pure] public override int GetHashCode(T? obj) => obj.GetHashCode(); internal override int IndexOf(T?[] array, T? value, int startIndex, int count) @@ -209,7 +202,6 @@ public override int GetHashCode() => [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] internal sealed class ObjectEqualityComparer : EqualityComparer { - [Pure] public override bool Equals(T x, T y) { if (x != null) @@ -221,7 +213,6 @@ public override bool Equals(T x, T y) return true; } - [Pure] public override int GetHashCode(T obj) => obj?.GetHashCode() ?? 0; internal override int IndexOf(T[] array, T value, int startIndex, int count) @@ -293,7 +284,6 @@ internal class NonRandomizedStringEqualityComparer : GenericEqualityComparer { - [Pure] public override bool Equals(byte x, byte y) { return x == y; } - [Pure] public override int GetHashCode(byte b) { return b.GetHashCode(); @@ -329,7 +317,6 @@ internal unsafe override int IndexOf(byte[] array, byte value, int startIndex, i throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); if (count > array.Length - startIndex) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.EndContractBlock(); if (count == 0) return -1; fixed (byte* pbytes = array) { @@ -359,7 +346,6 @@ public override int GetHashCode() => [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] internal class EnumEqualityComparer : EqualityComparer, ISerializable where T : struct { - [Pure] public override bool Equals(T x, T y) { int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(x); @@ -367,7 +353,6 @@ public override bool Equals(T x, T y) return x_final == y_final; } - [Pure] public override int GetHashCode(T obj) { int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj); @@ -428,7 +413,6 @@ public SByteEnumEqualityComparer() { } // This is used by the serialization engine. public SByteEnumEqualityComparer(SerializationInfo information, StreamingContext context) { } - [Pure] public override int GetHashCode(T obj) { int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj); @@ -445,7 +429,6 @@ public ShortEnumEqualityComparer() { } // This is used by the serialization engine. public ShortEnumEqualityComparer(SerializationInfo information, StreamingContext context) { } - [Pure] public override int GetHashCode(T obj) { int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj); @@ -457,7 +440,6 @@ public override int GetHashCode(T obj) [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] internal sealed class LongEnumEqualityComparer : EqualityComparer, ISerializable where T : struct { - [Pure] public override bool Equals(T x, T y) { long x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(x); @@ -465,7 +447,6 @@ public override bool Equals(T x, T y) return x_final == y_final; } - [Pure] public override int GetHashCode(T obj) { long x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(obj); diff --git a/src/mscorlib/src/System/Collections/Hashtable.cs b/src/mscorlib/src/System/Collections/Hashtable.cs index e2221857e461..0550030e7ca6 100644 --- a/src/mscorlib/src/System/Collections/Hashtable.cs +++ b/src/mscorlib/src/System/Collections/Hashtable.cs @@ -205,7 +205,6 @@ public Hashtable(int capacity, float loadFactor) throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum); if (!(loadFactor >= 0.1f && loadFactor <= 1.0f)) throw new ArgumentOutOfRangeException(nameof(loadFactor), SR.Format(SR.ArgumentOutOfRange_HashtableLoadFactor, .1, 1.0)); - Contract.EndContractBlock(); // Based on perf work, .72 is the optimal load factor for this table. this.loadFactor = 0.72f * loadFactor; @@ -344,7 +343,6 @@ public virtual bool ContainsKey(Object key) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } - Contract.EndContractBlock(); uint seed; uint incr; @@ -375,8 +373,8 @@ public virtual bool ContainsKey(Object key) // the KeyCollection class. private void CopyKeys(Array array, int arrayIndex) { - Contract.Requires(array != null); - Contract.Requires(array.Rank == 1); + Debug.Assert(array != null); + Debug.Assert(array.Rank == 1); bucket[] lbuckets = buckets; for (int i = lbuckets.Length; --i >= 0;) @@ -394,8 +392,8 @@ private void CopyKeys(Array array, int arrayIndex) // the KeyCollection class. private void CopyEntries(Array array, int arrayIndex) { - Contract.Requires(array != null); - Contract.Requires(array.Rank == 1); + Debug.Assert(array != null); + Debug.Assert(array.Rank == 1); bucket[] lbuckets = buckets; for (int i = lbuckets.Length; --i >= 0;) @@ -421,7 +419,6 @@ public virtual void CopyTo(Array array, int arrayIndex) throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - arrayIndex < Count) throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); - Contract.EndContractBlock(); CopyEntries(array, arrayIndex); } @@ -431,8 +428,8 @@ public virtual void CopyTo(Array array, int arrayIndex) // the ValueCollection class. private void CopyValues(Array array, int arrayIndex) { - Contract.Requires(array != null); - Contract.Requires(array.Rank == 1); + Debug.Assert(array != null); + Debug.Assert(array.Rank == 1); bucket[] lbuckets = buckets; for (int i = lbuckets.Length; --i >= 0;) @@ -456,7 +453,6 @@ public virtual Object this[Object key] { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } - Contract.EndContractBlock(); uint seed; uint incr; @@ -699,7 +695,6 @@ private void Insert(Object key, Object nvalue, bool add) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } - Contract.EndContractBlock(); if (count >= loadsize) { expand(); @@ -842,7 +837,6 @@ public virtual void Remove(Object key) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } - Contract.EndContractBlock(); Debug.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously! Don't do that - use Hashtable.Synchronized."); uint seed; @@ -908,7 +902,6 @@ public static Hashtable Synchronized(Hashtable table) { if (table == null) throw new ArgumentNullException(nameof(table)); - Contract.EndContractBlock(); return new SyncHashtable(table); } @@ -1038,7 +1031,6 @@ public virtual void CopyTo(Array array, int arrayIndex) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); if (array.Length - arrayIndex < _hashtable.count) throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); _hashtable.CopyKeys(array, arrayIndex); @@ -1084,7 +1076,6 @@ public virtual void CopyTo(Array array, int arrayIndex) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); if (array.Length - arrayIndex < _hashtable.count) throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); _hashtable.CopyValues(array, arrayIndex); @@ -1204,7 +1195,6 @@ public override bool ContainsKey(Object key) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } - Contract.EndContractBlock(); return _table.ContainsKey(key); } @@ -1449,7 +1439,6 @@ public static int GetPrime(int min) { if (min < 0) throw new ArgumentException(SR.Arg_HTCapacityOverflow); - Contract.EndContractBlock(); for (int i = 0; i < primes.Length; i++) { diff --git a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs b/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs index b3eb00689841..2337439dda62 100644 --- a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs +++ b/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs @@ -15,7 +15,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Collections.ObjectModel { @@ -37,7 +36,6 @@ public ReadOnlyDictionary(IDictionary dictionary) { throw new ArgumentNullException(nameof(dictionary)); } - Contract.EndContractBlock(); m_dictionary = dictionary; } @@ -50,7 +48,6 @@ public KeyCollection Keys { get { - Contract.Ensures(Contract.Result() != null); if (m_keys == null) { m_keys = new KeyCollection(m_dictionary.Keys); @@ -63,7 +60,6 @@ public ValueCollection Values { get { - Contract.Ensures(Contract.Result() != null); if (m_values == null) { m_values = new ValueCollection(m_dictionary.Values); diff --git a/src/mscorlib/src/System/DateTime.CoreCLR.cs b/src/mscorlib/src/System/DateTime.CoreCLR.cs index 69c595663b27..4d36b9970a9c 100644 --- a/src/mscorlib/src/System/DateTime.CoreCLR.cs +++ b/src/mscorlib/src/System/DateTime.CoreCLR.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; namespace System @@ -13,7 +12,6 @@ public static DateTime UtcNow { get { - Contract.Ensures(Contract.Result().Kind == DateTimeKind.Utc); // following code is tuned for speed. Don't change it without running benchmark. long ticks = 0; ticks = GetSystemTimeAsFileTime(); diff --git a/src/mscorlib/src/System/Decimal.cs b/src/mscorlib/src/System/Decimal.cs index 5bb0446784db..e93971d1c051 100644 --- a/src/mscorlib/src/System/Decimal.cs +++ b/src/mscorlib/src/System/Decimal.cs @@ -10,7 +10,7 @@ using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Runtime.Serialization; -using System.Diagnostics.Contracts; +using System.Diagnostics; namespace System { @@ -275,7 +275,6 @@ private void SetBits(int[] bits) { if (bits == null) throw new ArgumentNullException(nameof(bits)); - Contract.EndContractBlock(); if (bits.Length == 4) { int f = bits[3]; @@ -297,7 +296,6 @@ public Decimal(int lo, int mid, int hi, bool isNegative, byte scale) { if (scale > 28) throw new ArgumentOutOfRangeException(nameof(scale), SR.ArgumentOutOfRange_DecimalScale); - Contract.EndContractBlock(); this.lo = lo; this.mid = mid; this.hi = hi; @@ -478,25 +476,21 @@ public static Decimal Floor(Decimal d) // public override String ToString() { - Contract.Ensures(Contract.Result() != null); return Number.FormatDecimal(this, null, NumberFormatInfo.CurrentInfo); } public String ToString(String format) { - Contract.Ensures(Contract.Result() != null); return Number.FormatDecimal(this, format, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatDecimal(this, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format, IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); return Number.FormatDecimal(this, format, NumberFormatInfo.GetInstance(provider)); } @@ -587,7 +581,7 @@ public static int[] GetBits(Decimal d) internal static void GetBytes(Decimal d, byte[] buffer) { - Contract.Requires((buffer != null && buffer.Length >= 16), "[GetBytes]buffer != null && buffer.Length >= 16"); + Debug.Assert((buffer != null && buffer.Length >= 16), "[GetBytes]buffer != null && buffer.Length >= 16"); buffer[0] = (byte)d.lo; buffer[1] = (byte)(d.lo >> 8); buffer[2] = (byte)(d.lo >> 16); @@ -611,7 +605,7 @@ internal static void GetBytes(Decimal d, byte[] buffer) internal static decimal ToDecimal(byte[] buffer) { - Contract.Requires((buffer != null && buffer.Length >= 16), "[ToDecimal]buffer != null && buffer.Length >= 16"); + Debug.Assert((buffer != null && buffer.Length >= 16), "[ToDecimal]buffer != null && buffer.Length >= 16"); int lo = ((int)buffer[0]) | ((int)buffer[1] << 8) | ((int)buffer[2] << 16) | ((int)buffer[3] << 24); int mid = ((int)buffer[4]) | ((int)buffer[5] << 8) | ((int)buffer[6] << 16) | ((int)buffer[7] << 24); int hi = ((int)buffer[8]) | ((int)buffer[9] << 8) | ((int)buffer[10] << 16) | ((int)buffer[11] << 24); @@ -818,7 +812,6 @@ public static Decimal Round(Decimal d, int decimals, MidpointRounding mode) { throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode)); } - Contract.EndContractBlock(); if (mode == MidpointRounding.ToEven) { diff --git a/src/mscorlib/src/System/Delegate.cs b/src/mscorlib/src/System/Delegate.cs index 8a9763694bea..188657aa7a2a 100644 --- a/src/mscorlib/src/System/Delegate.cs +++ b/src/mscorlib/src/System/Delegate.cs @@ -13,7 +13,6 @@ namespace System using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Diagnostics; - using System.Diagnostics.Contracts; [ClassInterface(ClassInterfaceType.AutoDual)] [System.Runtime.InteropServices.ComVisible(true)] @@ -45,7 +44,6 @@ protected Delegate(Object target, String method) if (method == null) throw new ArgumentNullException(nameof(method)); - Contract.EndContractBlock(); // This API existed in v1/v1.1 and only expected to create closed // instance delegates. Constrain the call to BindToMethodName to @@ -72,7 +70,6 @@ protected unsafe Delegate(Type target, String method) if (method == null) throw new ArgumentNullException(nameof(method)); - Contract.EndContractBlock(); RuntimeType rtTarget = target as RuntimeType; if (rtTarget == null) @@ -349,7 +346,6 @@ public static Delegate CreateDelegate(Type type, Object target, String method, b throw new ArgumentNullException(nameof(target)); if (method == null) throw new ArgumentNullException(nameof(method)); - Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; if (rtType == null) @@ -402,7 +398,6 @@ public static Delegate CreateDelegate(Type type, Type target, String method, boo throw new ArgumentException(SR.Arg_UnboundGenParam, nameof(target)); if (method == null) throw new ArgumentNullException(nameof(method)); - Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; RuntimeType rtTarget = target as RuntimeType; @@ -440,7 +435,6 @@ public static Delegate CreateDelegate(Type type, MethodInfo method, bool throwOn throw new ArgumentNullException(nameof(type)); if (method == null) throw new ArgumentNullException(nameof(method)); - Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; if (rtType == null) @@ -490,7 +484,6 @@ public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInf throw new ArgumentNullException(nameof(type)); if (method == null) throw new ArgumentNullException(nameof(method)); - Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; if (rtType == null) @@ -558,7 +551,6 @@ internal unsafe static Delegate CreateDelegateNoSecurityCheck(Type type, Object // Validate the parameters. if (type == null) throw new ArgumentNullException(nameof(type)); - Contract.EndContractBlock(); if (method.IsNullHandle()) throw new ArgumentNullException(nameof(method)); @@ -594,7 +586,6 @@ internal static Delegate CreateDelegateNoSecurityCheck(RuntimeType type, Object if (method == null) throw new ArgumentNullException(nameof(method)); - Contract.EndContractBlock(); RuntimeMethodInfo rtMethod = method as RuntimeMethodInfo; if (rtMethod == null) diff --git a/src/mscorlib/src/System/Diagnostics/Assert.cs b/src/mscorlib/src/System/Diagnostics/Assert.cs index 67e6914aa478..3fbbdc98303a 100644 --- a/src/mscorlib/src/System/Diagnostics/Assert.cs +++ b/src/mscorlib/src/System/Diagnostics/Assert.cs @@ -7,7 +7,6 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; -using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics diff --git a/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs b/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs index 32a417036f55..5b74f601b124 100644 --- a/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs +++ b/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs @@ -646,7 +646,6 @@ public static bool ForAll(int fromInclusive, int toExclusive, Predicate pre #endif if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - Contract.EndContractBlock(); for (int i = fromInclusive; i < toExclusive; i++) if (!predicate(i)) return false; @@ -672,7 +671,6 @@ public static bool ForAll(IEnumerable collection, Predicate predicate) throw new ArgumentNullException(nameof(collection)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - Contract.EndContractBlock(); foreach (T t in collection) if (!predicate(t)) return false; @@ -706,7 +704,6 @@ public static bool Exists(int fromInclusive, int toExclusive, Predicate pre #endif if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - Contract.EndContractBlock(); for (int i = fromInclusive; i < toExclusive; i++) if (predicate(i)) return true; @@ -731,7 +728,6 @@ public static bool Exists(IEnumerable collection, Predicate predicate) throw new ArgumentNullException(nameof(collection)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - Contract.EndContractBlock(); foreach (T t in collection) if (predicate(t)) return true; diff --git a/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs b/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs index db6a40c54a1a..e4bbe1d71e9a 100644 --- a/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs +++ b/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs @@ -96,7 +96,6 @@ static partial void ReportFailure(ContractFailureKind failureKind, String userMe { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind)); - Contract.EndContractBlock(); // displayMessage == null means: yes we handled it. Otherwise it is the localized failure message var displayMessage = System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); @@ -148,7 +147,7 @@ public sealed class ContractFailedEventArgs : EventArgs #endif public ContractFailedEventArgs(ContractFailureKind failureKind, String message, String condition, Exception originalException) { - Contract.Requires(originalException == null || failureKind == ContractFailureKind.PostconditionOnException); + Debug.Assert(originalException == null || failureKind == ContractFailureKind.PostconditionOnException); _failureKind = failureKind; _message = message; _condition = condition; @@ -296,7 +295,6 @@ static partial void RaiseContractFailedEventImplementation(ContractFailureKind f { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind)); - Contract.EndContractBlock(); string returnValue; String displayMessage = "contract failed."; // Incomplete, but in case of OOM during resource lookup... @@ -405,7 +403,7 @@ private static String GetResourceNameForFailure(ContractFailureKind failureKind) break; default: - Contract.Assume(false, "Unreachable code"); + Debug.Fail("Unreachable code"); resourceName = "AssumptionFailed"; break; } diff --git a/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs b/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs index 34e65bcb3e34..035f809b2126 100644 --- a/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs +++ b/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs @@ -14,7 +14,6 @@ using System; using System.Runtime.InteropServices; -using System.Diagnostics.Contracts; namespace System.Diagnostics { @@ -126,7 +125,6 @@ public DebuggerBrowsableAttribute(DebuggerBrowsableState state) { if (state < DebuggerBrowsableState.Never || state > DebuggerBrowsableState.RootHidden) throw new ArgumentOutOfRangeException(nameof(state)); - Contract.EndContractBlock(); this.state = state; } @@ -151,7 +149,6 @@ public DebuggerTypeProxyAttribute(Type type) { throw new ArgumentNullException(nameof(type)); } - Contract.EndContractBlock(); typeName = type.AssemblyQualifiedName; } @@ -173,7 +170,6 @@ public Type Target { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); targetName = value.AssemblyQualifiedName; target = value; @@ -246,7 +242,6 @@ public Type Target { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); targetName = value.AssemblyQualifiedName; target = value; diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/XplatEventLogger.cs b/src/mscorlib/src/System/Diagnostics/Eventing/XplatEventLogger.cs index 00155d72a0cb..d8057f36de28 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/XplatEventLogger.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/XplatEventLogger.cs @@ -7,13 +7,10 @@ using System.Runtime.InteropServices; using System.Runtime.Versioning; -using Contract = System.Diagnostics.Contracts.Contract; - #if FEATURE_EVENTSOURCE_XPLAT namespace System.Diagnostics.Tracing { - internal class XplatEventLogger : EventListener { private static Lazy eventSourceNameFilter = new Lazy(() => CompatibilitySwitch.GetValueInternal("EventSourceFilter")); @@ -26,7 +23,6 @@ public XplatEventLogger() {} public static EventListener InitializePersistentListener() { try{ - if (!initializedPersistentListener && XplatEventLogger.IsEventSourceLoggingEnabled()) { initializedPersistentListener = true; diff --git a/src/mscorlib/src/System/Diagnostics/LogSwitch.cs b/src/mscorlib/src/System/Diagnostics/LogSwitch.cs index d3994d48b850..5382c37547a4 100644 --- a/src/mscorlib/src/System/Diagnostics/LogSwitch.cs +++ b/src/mscorlib/src/System/Diagnostics/LogSwitch.cs @@ -6,7 +6,6 @@ using System.IO; using System.Collections; using System.Runtime.Versioning; -using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics @@ -37,7 +36,6 @@ public LogSwitch(String name, String description, LogSwitch parent) { if (name != null && name.Length == 0) throw new ArgumentOutOfRangeException(nameof(Name), SR.Argument_StringZeroLength); - Contract.EndContractBlock(); if ((name != null) && (parent != null)) { diff --git a/src/mscorlib/src/System/Diagnostics/Stackframe.cs b/src/mscorlib/src/System/Diagnostics/Stackframe.cs index a6a7067af347..f45de5cab9b5 100644 --- a/src/mscorlib/src/System/Diagnostics/Stackframe.cs +++ b/src/mscorlib/src/System/Diagnostics/Stackframe.cs @@ -7,7 +7,6 @@ using System; using System.IO; using System.Reflection; -using System.Diagnostics.Contracts; namespace System.Diagnostics { @@ -149,8 +148,6 @@ internal virtual bool GetIsLastFrameFromForeignExceptionStackTrace() // public virtual MethodBase GetMethod() { - Contract.Ensures(Contract.Result() != null); - return method; } diff --git a/src/mscorlib/src/System/Diagnostics/Stacktrace.cs b/src/mscorlib/src/System/Diagnostics/Stacktrace.cs index 097ed44f85b0..022c72ce013b 100644 --- a/src/mscorlib/src/System/Diagnostics/Stacktrace.cs +++ b/src/mscorlib/src/System/Diagnostics/Stacktrace.cs @@ -14,7 +14,6 @@ using System.Globalization; using System.Runtime.Serialization; using System.Runtime.Versioning; -using System.Diagnostics.Contracts; namespace System.Diagnostics { @@ -279,7 +278,6 @@ public StackTrace(int skipFrames) if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; @@ -295,7 +293,6 @@ public StackTrace(int skipFrames, bool fNeedFileInfo) if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; @@ -309,7 +306,6 @@ public StackTrace(Exception e) { if (e == null) throw new ArgumentNullException(nameof(e)); - Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; @@ -322,7 +318,6 @@ public StackTrace(Exception e, bool fNeedFileInfo) { if (e == null) throw new ArgumentNullException(nameof(e)); - Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; @@ -340,7 +335,6 @@ public StackTrace(Exception e, int skipFrames) if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; @@ -359,7 +353,6 @@ public StackTrace(Exception e, int skipFrames, bool fNeedFileInfo) if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; diff --git a/src/mscorlib/src/System/Diagnostics/log.cs b/src/mscorlib/src/System/Diagnostics/log.cs index 5ed3a3e502f4..f38eaccabc2e 100644 --- a/src/mscorlib/src/System/Diagnostics/log.cs +++ b/src/mscorlib/src/System/Diagnostics/log.cs @@ -10,7 +10,6 @@ namespace System.Diagnostics using System.Runtime.CompilerServices; using Encoding = System.Text.Encoding; using System.Runtime.Versioning; - using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; using Console = Internal.Console; @@ -87,7 +86,6 @@ public static void LogMessage(LoggingLevels level, LogSwitch logswitch, String m if (level < 0) throw new ArgumentOutOfRangeException(nameof(level), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); // Is logging for this level for this switch enabled? if (logswitch.CheckLevel(level) == true) diff --git a/src/mscorlib/src/System/Empty.cs b/src/mscorlib/src/System/Empty.cs index 2b585b314104..ac01fa6f5c5a 100644 --- a/src/mscorlib/src/System/Empty.cs +++ b/src/mscorlib/src/System/Empty.cs @@ -6,7 +6,6 @@ // This class represents an empty variant //////////////////////////////////////////////////////////////////////////////// -using System.Diagnostics.Contracts; using System; using System.Runtime.Serialization; diff --git a/src/mscorlib/src/System/Enum.cs b/src/mscorlib/src/System/Enum.cs index b5d00fe60edb..96bf31c88986 100644 --- a/src/mscorlib/src/System/Enum.cs +++ b/src/mscorlib/src/System/Enum.cs @@ -10,7 +10,6 @@ using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics; -using System.Diagnostics.Contracts; // The code below includes partial support for float/double and // pointer sized enums. @@ -122,7 +121,7 @@ private static String InternalFormattedHexString(object value) internal static String GetEnumName(RuntimeType eT, ulong ulValue) { - Contract.Requires(eT != null); + Debug.Assert(eT != null); ulong[] ulValues = Enum.InternalGetValues(eT); int index = Array.BinarySearch(ulValues, ulValue); @@ -137,7 +136,7 @@ internal static String GetEnumName(RuntimeType eT, ulong ulValue) private static String InternalFormat(RuntimeType eT, ulong value) { - Contract.Requires(eT != null); + Debug.Assert(eT != null); // These values are sorted by value. Don't change this TypeValuesAndNames entry = GetCachedValuesAndNames(eT, true); @@ -162,7 +161,7 @@ private static String InternalFlagsFormat(RuntimeType eT, ulong result) private static String InternalFlagsFormat(RuntimeType eT, TypeValuesAndNames entry, ulong result) { - Contract.Requires(eT != null); + Debug.Assert(eT != null); String[] names = entry.Names; ulong[] values = entry.Values; @@ -411,7 +410,6 @@ private static bool TryParseEnum(Type enumType, String value, bool ignoreCase, r { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); - Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) @@ -547,8 +545,6 @@ public static Type GetUnderlyingType(Type enumType) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return enumType.GetEnumUnderlyingType(); } @@ -557,8 +553,6 @@ public static Array GetValues(Type enumType) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return enumType.GetEnumValues(); } @@ -573,7 +567,6 @@ public static String GetName(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); - Contract.EndContractBlock(); return enumType.GetEnumName(value); } @@ -582,8 +575,6 @@ public static String[] GetNames(Type enumType) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return enumType.GetEnumNames(); } @@ -598,7 +589,6 @@ public static Object ToObject(Type enumType, Object value) { if (value == null) throw new ArgumentNullException(nameof(value)); - Contract.EndContractBlock(); // Delegate rest of error checking to the other functions TypeCode typeCode = Convert.GetTypeCode(value); @@ -641,12 +631,10 @@ public static Object ToObject(Type enumType, Object value) } } - [Pure] public static bool IsDefined(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); - Contract.EndContractBlock(); return enumType.IsEnumDefined(value); } @@ -664,7 +652,6 @@ public static String Format(Type enumType, Object value, String format) if (format == null) throw new ArgumentNullException(nameof(format)); - Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) @@ -915,7 +902,6 @@ public int CompareTo(Object target) if (this == null) throw new NullReferenceException(); - Contract.EndContractBlock(); int ret = InternalCompareTo(this, target); @@ -978,7 +964,6 @@ public Boolean HasFlag(Enum flag) { if (flag == null) throw new ArgumentNullException(nameof(flag)); - Contract.EndContractBlock(); if (!this.GetType().IsEquivalentTo(flag.GetType())) { @@ -1104,7 +1089,6 @@ public static Object ToObject(Type enumType, sbyte value) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); - Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); @@ -1117,7 +1101,6 @@ public static Object ToObject(Type enumType, short value) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); - Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); @@ -1130,7 +1113,6 @@ public static Object ToObject(Type enumType, int value) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); - Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); @@ -1143,7 +1125,6 @@ public static Object ToObject(Type enumType, byte value) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); - Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); @@ -1157,7 +1138,6 @@ public static Object ToObject(Type enumType, ushort value) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); - Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); @@ -1171,7 +1151,6 @@ public static Object ToObject(Type enumType, uint value) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); - Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); @@ -1184,7 +1163,6 @@ public static Object ToObject(Type enumType, long value) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); - Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); @@ -1198,7 +1176,6 @@ public static Object ToObject(Type enumType, ulong value) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); - Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); @@ -1211,7 +1188,6 @@ private static Object ToObject(Type enumType, char value) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); - Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); @@ -1224,7 +1200,6 @@ private static Object ToObject(Type enumType, bool value) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); - Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); diff --git a/src/mscorlib/src/System/Environment.cs b/src/mscorlib/src/System/Environment.cs index ea99a1e3f27f..4ea73e4d9c45 100644 --- a/src/mscorlib/src/System/Environment.cs +++ b/src/mscorlib/src/System/Environment.cs @@ -30,7 +30,6 @@ namespace System using System.Threading; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; - using System.Diagnostics.Contracts; public enum EnvironmentVariableTarget { @@ -135,7 +134,6 @@ public static String ExpandEnvironmentVariables(String name) { if (name == null) throw new ArgumentNullException(nameof(name)); - Contract.EndContractBlock(); if (name.Length == 0) { @@ -289,7 +287,6 @@ public static String NewLine { get { - Contract.Ensures(Contract.Result() != null); #if PLATFORM_WINDOWS return "\r\n"; #else @@ -362,7 +359,6 @@ public static String StackTrace [MethodImpl(MethodImplOptions.NoInlining)] // Prevent inlining from affecting where the stacktrace starts get { - Contract.Ensures(Contract.Result() != null); return Internal.Runtime.Augments.EnvironmentAugments.StackTrace; } } diff --git a/src/mscorlib/src/System/Exception.cs b/src/mscorlib/src/System/Exception.cs index 785637d1bac8..79a581271da5 100644 --- a/src/mscorlib/src/System/Exception.cs +++ b/src/mscorlib/src/System/Exception.cs @@ -25,7 +25,6 @@ namespace System using System.Reflection; using System.Collections; using System.Globalization; - using System.Diagnostics.Contracts; [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] @@ -74,7 +73,6 @@ protected Exception(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); - Contract.EndContractBlock(); _className = info.GetString("ClassName"); // Do not rename (binary serialization) _message = info.GetString("Message"); // Do not rename (binary serialization) @@ -439,7 +437,6 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte { throw new ArgumentNullException(nameof(info)); } - Contract.EndContractBlock(); String tempStackTraceString = _stackTraceString; diff --git a/src/mscorlib/src/System/GC.cs b/src/mscorlib/src/System/GC.cs index 11ae8bf32e72..5f95a22ee713 100644 --- a/src/mscorlib/src/System/GC.cs +++ b/src/mscorlib/src/System/GC.cs @@ -24,7 +24,6 @@ using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Versioning; -using System.Diagnostics.Contracts; namespace System { @@ -119,7 +118,6 @@ public static void AddMemoryPressure(long bytesAllocated) throw new ArgumentOutOfRangeException("pressure", SR.ArgumentOutOfRange_MustBeNonNegInt32); } - Contract.EndContractBlock(); _AddMemoryPressure((ulong)bytesAllocated); } @@ -137,7 +135,6 @@ public static void RemoveMemoryPressure(long bytesAllocated) throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_MustBeNonNegInt32); } - Contract.EndContractBlock(); _RemoveMemoryPressure((ulong)bytesAllocated); } @@ -186,7 +183,6 @@ public static void Collect(int generation, GCCollectionMode mode, bool blocking, throw new ArgumentOutOfRangeException(nameof(mode), SR.ArgumentOutOfRange_Enum); } - Contract.EndContractBlock(); int iInternalModes = 0; @@ -216,7 +212,6 @@ public static int CollectionCount(int generation) { throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive); } - Contract.EndContractBlock(); return _CollectionCount(generation, 0); } @@ -295,7 +290,6 @@ public static void SuppressFinalize(Object obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); - Contract.EndContractBlock(); _SuppressFinalize(obj); } @@ -310,7 +304,6 @@ public static void ReRegisterForFinalize(Object obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); - Contract.EndContractBlock(); _ReRegisterForFinalize(obj); } diff --git a/src/mscorlib/src/System/Globalization/CalendarData.Windows.cs b/src/mscorlib/src/System/Globalization/CalendarData.Windows.cs index 89de24d9d7cb..952f63f80bca 100644 --- a/src/mscorlib/src/System/Globalization/CalendarData.Windows.cs +++ b/src/mscorlib/src/System/Globalization/CalendarData.Windows.cs @@ -6,7 +6,6 @@ using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; -using System.Diagnostics.Contracts; using System.Collections.Generic; namespace System.Globalization diff --git a/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs b/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs index 8e3bb474240c..3881272287d0 100644 --- a/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs +++ b/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs @@ -13,7 +13,6 @@ //////////////////////////////////////////////////////////////////////////// using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Globalization { @@ -232,7 +231,6 @@ public static double GetNumericValue(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } - Contract.EndContractBlock(); return (InternalGetNumericValue(InternalConvertToUtf32(s, index))); } @@ -252,7 +250,6 @@ public static int GetDecimalDigitValue(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } - Contract.EndContractBlock(); return (sbyte)(InternalGetDigitValues(InternalConvertToUtf32(s, index)) >> 8); } @@ -274,7 +271,6 @@ public static int GetDigitValue(String s, int index) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } - Contract.EndContractBlock(); return (sbyte)(InternalGetDigitValues(InternalConvertToUtf32(s, index)) & 0x00FF); } @@ -291,7 +287,6 @@ public static UnicodeCategory GetUnicodeCategory(String s, int index) { throw new ArgumentOutOfRangeException(nameof(index)); } - Contract.EndContractBlock(); return InternalGetUnicodeCategory(s, index); } diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.Invariant.cs b/src/mscorlib/src/System/Globalization/CompareInfo.Invariant.cs index 2a20de76bb5a..13725bcc51f4 100644 --- a/src/mscorlib/src/System/Globalization/CompareInfo.Invariant.cs +++ b/src/mscorlib/src/System/Globalization/CompareInfo.Invariant.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Globalization { @@ -199,7 +198,6 @@ private static char InvariantToUpper(char c) private unsafe SortKey InvariantCreateSortKey(string source, CompareOptions options) { if (source == null) { throw new ArgumentNullException(nameof(source)); } - Contract.EndContractBlock(); if ((options & ValidSortkeyCtorMaskOffFlags) != 0) { diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.Unix.cs b/src/mscorlib/src/System/Globalization/CompareInfo.Unix.cs index 92fd691c8b24..612c99e98e50 100644 --- a/src/mscorlib/src/System/Globalization/CompareInfo.Unix.cs +++ b/src/mscorlib/src/System/Globalization/CompareInfo.Unix.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; @@ -280,7 +279,6 @@ private unsafe SortKey CreateSortKey(String source, CompareOptions options) Debug.Assert(!_invariantMode); if (source==null) { throw new ArgumentNullException(nameof(source)); } - Contract.EndContractBlock(); if ((options & ValidSortkeyCtorMaskOffFlags) != 0) { diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs b/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs index 2bfe15b835ac..6fdb8b20e6f1 100644 --- a/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs +++ b/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs @@ -4,7 +4,6 @@ using System.Security; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -377,7 +376,6 @@ private unsafe SortKey CreateSortKey(String source, CompareOptions options) Debug.Assert(!_invariantMode); if (source == null) { throw new ArgumentNullException(nameof(source)); } - Contract.EndContractBlock(); if ((options & ValidSortkeyCtorMaskOffFlags) != 0) { diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.cs b/src/mscorlib/src/System/Globalization/CompareInfo.cs index bfdbdc546bdc..1b794eceeadb 100644 --- a/src/mscorlib/src/System/Globalization/CompareInfo.cs +++ b/src/mscorlib/src/System/Globalization/CompareInfo.cs @@ -14,7 +14,6 @@ using System.Reflection; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System.Globalization @@ -107,7 +106,6 @@ public static CompareInfo GetCompareInfo(int culture, Assembly assembly) { throw new ArgumentException(SR.Argument_OnlyMscorlib); } - Contract.EndContractBlock(); return GetCompareInfo(culture); } @@ -130,7 +128,6 @@ public static CompareInfo GetCompareInfo(string name, Assembly assembly) { throw new ArgumentNullException(name == null ? nameof(name) : nameof(assembly)); } - Contract.EndContractBlock(); if (assembly != typeof(Object).Module.Assembly) { @@ -176,7 +173,6 @@ public static CompareInfo GetCompareInfo(string name) { throw new ArgumentNullException(nameof(name)); } - Contract.EndContractBlock(); return CultureInfo.GetCultureInfo(name).CompareInfo; } @@ -254,7 +250,7 @@ private void OnSerializing(StreamingContext ctx) { // This is merely for serialization compatibility with Whidbey/Orcas, it can go away when we don't want that compat any more. culture = CultureInfo.GetCultureInfo(this.Name).LCID; // This is the lcid of the constructing culture (still have to dereference to get target sort) - Contract.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already"); + Debug.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already"); } ///////////////////////////----- Name -----///////////////////////////////// @@ -540,7 +536,6 @@ public virtual bool IsPrefix(string source, string prefix, CompareOptions option throw new ArgumentNullException((source == null ? nameof(source) : nameof(prefix)), SR.ArgumentNull_String); } - Contract.EndContractBlock(); if (prefix.Length == 0) { @@ -595,7 +590,6 @@ public virtual bool IsSuffix(string source, string suffix, CompareOptions option throw new ArgumentNullException((source == null ? nameof(source) : nameof(suffix)), SR.ArgumentNull_String); } - Contract.EndContractBlock(); if (suffix.Length == 0) { @@ -654,7 +648,6 @@ public virtual int IndexOf(string source, char value) { if (source == null) throw new ArgumentNullException(nameof(source)); - Contract.EndContractBlock(); return IndexOf(source, value, 0, source.Length, CompareOptions.None); } @@ -664,7 +657,6 @@ public virtual int IndexOf(string source, string value) { if (source == null) throw new ArgumentNullException(nameof(source)); - Contract.EndContractBlock(); return IndexOf(source, value, 0, source.Length, CompareOptions.None); } @@ -674,7 +666,6 @@ public virtual int IndexOf(string source, char value, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); - Contract.EndContractBlock(); return IndexOf(source, value, 0, source.Length, options); } @@ -684,7 +675,6 @@ public virtual int IndexOf(string source, string value, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); - Contract.EndContractBlock(); return IndexOf(source, value, 0, source.Length, options); } @@ -693,7 +683,6 @@ public virtual int IndexOf(string source, char value, int startIndex) { if (source == null) throw new ArgumentNullException(nameof(source)); - Contract.EndContractBlock(); return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None); } @@ -702,7 +691,6 @@ public virtual int IndexOf(string source, string value, int startIndex) { if (source == null) throw new ArgumentNullException(nameof(source)); - Contract.EndContractBlock(); return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None); } @@ -711,7 +699,6 @@ public virtual int IndexOf(string source, char value, int startIndex, CompareOpt { if (source == null) throw new ArgumentNullException(nameof(source)); - Contract.EndContractBlock(); return IndexOf(source, value, startIndex, source.Length - startIndex, options); } @@ -721,7 +708,6 @@ public virtual int IndexOf(string source, string value, int startIndex, CompareO { if (source == null) throw new ArgumentNullException(nameof(source)); - Contract.EndContractBlock(); return IndexOf(source, value, startIndex, source.Length - startIndex, options); } @@ -749,7 +735,6 @@ public unsafe virtual int IndexOf(string source, char value, int startIndex, int if (count < 0 || startIndex > source.Length - count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); - Contract.EndContractBlock(); if (options == CompareOptions.OrdinalIgnoreCase) { @@ -779,7 +764,6 @@ public unsafe virtual int IndexOf(string source, string value, int startIndex, i { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); } - Contract.EndContractBlock(); // In Everett we used to return -1 for empty string even if startIndex is negative number so we keeping same behavior here. // We return 0 if both source and value are empty strings for Everett compatibility too. @@ -891,7 +875,6 @@ public virtual int LastIndexOf(String source, char value) { if (source == null) throw new ArgumentNullException(nameof(source)); - Contract.EndContractBlock(); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, source.Length, CompareOptions.None); @@ -902,7 +885,6 @@ public virtual int LastIndexOf(string source, string value) { if (source == null) throw new ArgumentNullException(nameof(source)); - Contract.EndContractBlock(); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, @@ -914,7 +896,6 @@ public virtual int LastIndexOf(string source, char value, CompareOptions options { if (source == null) throw new ArgumentNullException(nameof(source)); - Contract.EndContractBlock(); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, @@ -925,7 +906,6 @@ public virtual int LastIndexOf(string source, string value, CompareOptions optio { if (source == null) throw new ArgumentNullException(nameof(source)); - Contract.EndContractBlock(); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, source.Length, options); @@ -971,7 +951,6 @@ public virtual int LastIndexOf(string source, char value, int startIndex, int co // Verify Arguments if (source == null) throw new ArgumentNullException(nameof(source)); - Contract.EndContractBlock(); // Validate CompareOptions // Ordinal can't be selected with other flags @@ -1019,7 +998,6 @@ public virtual int LastIndexOf(string source, string value, int startIndex, int throw new ArgumentNullException(nameof(source)); if (value == null) throw new ArgumentNullException(nameof(value)); - Contract.EndContractBlock(); // Validate CompareOptions // Ordinal can't be selected with other flags @@ -1176,7 +1154,6 @@ internal int GetHashCodeOfString(string source, CompareOptions options) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } - Contract.EndContractBlock(); return GetHashCodeOfStringCore(source, options); } diff --git a/src/mscorlib/src/System/Globalization/CultureInfo.cs b/src/mscorlib/src/System/Globalization/CultureInfo.cs index fd879c709d6c..fb7176abe0cb 100644 --- a/src/mscorlib/src/System/Globalization/CultureInfo.cs +++ b/src/mscorlib/src/System/Globalization/CultureInfo.cs @@ -28,7 +28,6 @@ using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.Serialization; using System.Threading; @@ -236,7 +235,6 @@ public CultureInfo(int culture, bool useUserOverride) { throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum); } - Contract.EndContractBlock(); InitializeFromCultureId(culture, useUserOverride); } @@ -289,7 +287,6 @@ internal CultureInfo(String cultureName, String textAndCompareCultureName) { throw new ArgumentNullException(nameof(cultureName),SR.ArgumentNull_String); } - Contract.EndContractBlock(); _cultureData = CultureData.GetCultureData(cultureName, false); if (_cultureData == null) @@ -337,8 +334,6 @@ private static CultureInfo GetCultureByName(String name, bool userOverride) // public static CultureInfo CreateSpecificCulture(String name) { - Contract.Ensures(Contract.Result() != null); - CultureInfo culture; try @@ -481,7 +476,6 @@ public static CultureInfo InstalledUICulture { get { - Contract.Ensures(Contract.Result() != null); if (s_userDefaultCulture == null) { Init(); @@ -600,7 +594,6 @@ public virtual int KeyboardLayoutId public static CultureInfo[] GetCultures(CultureTypes types) { - Contract.Ensures(Contract.Result() != null); // internally we treat UserCustomCultures as Supplementals but v2 // treats as Supplementals and Replacements if ((types & CultureTypes.UserCustomCulture) == CultureTypes.UserCustomCulture) @@ -653,8 +646,6 @@ public string IetfLanguageTag { get { - Contract.Ensures(Contract.Result() != null); - // special case the compatibility cultures switch (this.Name) { @@ -681,7 +672,6 @@ public virtual String DisplayName { get { - Contract.Ensures(Contract.Result() != null); Debug.Assert(_name != null, "[CultureInfo.DisplayName] Always expect _name to be set"); return _cultureData.SLOCALIZEDDISPLAYNAME; @@ -701,7 +691,6 @@ public virtual String NativeName { get { - Contract.Ensures(Contract.Result() != null); return (_cultureData.SNATIVEDISPLAYNAME); } } @@ -719,7 +708,6 @@ public virtual String EnglishName { get { - Contract.Ensures(Contract.Result() != null); return (_cultureData.SENGDISPLAYNAME); } } @@ -729,7 +717,6 @@ public virtual String TwoLetterISOLanguageName { get { - Contract.Ensures(Contract.Result() != null); return (_cultureData.SISO639LANGNAME); } } @@ -739,7 +726,6 @@ public virtual String ThreeLetterISOLanguageName { get { - Contract.Ensures(Contract.Result() != null); return _cultureData.SISO639LANGNAME2; } } @@ -756,7 +742,6 @@ public virtual String ThreeLetterWindowsLanguageName { get { - Contract.Ensures(Contract.Result() != null); return _cultureData.SABBREVLANGNAME; } } @@ -1094,8 +1079,6 @@ public virtual Calendar[] OptionalCalendars { get { - Contract.Ensures(Contract.Result() != null); - // // This property always returns a new copy of the calendar array. // @@ -1119,8 +1102,6 @@ public bool UseUserOverride public CultureInfo GetConsoleFallbackUICulture() { - Contract.Ensures(Contract.Result() != null); - CultureInfo temp = _consoleFallbackCulture; if (temp == null) { @@ -1174,8 +1155,6 @@ public static CultureInfo ReadOnly(CultureInfo ci) { throw new ArgumentNullException(nameof(ci)); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); if (ci.IsReadOnly) { @@ -1398,8 +1377,6 @@ public static CultureInfo GetCultureInfo(int culture) { throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); CultureInfo retval = GetCultureInfoHelper(culture, null, null); if (null == retval) { @@ -1442,8 +1419,6 @@ public static CultureInfo GetCultureInfo(string name, string altName) throw new ArgumentNullException(nameof(altName)); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); CultureInfo retval = GetCultureInfoHelper(-1, name, altName); if (retval == null) @@ -1457,8 +1432,6 @@ public static CultureInfo GetCultureInfo(string name, string altName) // This function is deprecated, we don't like it public static CultureInfo GetCultureInfoByIetfLanguageTag(string name) { - Contract.Ensures(Contract.Result() != null); - // Disallow old zh-CHT/zh-CHS names if (name == "zh-CHT" || name == "zh-CHS") { diff --git a/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs b/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs index dc61c9f0d9cb..f9671cc68484 100644 --- a/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs +++ b/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Text; namespace System.Globalization @@ -33,7 +32,6 @@ internal static int GetCodePageFromName(string name) { throw new ArgumentNullException(nameof(name)); } - Contract.EndContractBlock(); ushort codePage; if (s_encodingDataTable.TryGetValue(name, out codePage)) diff --git a/src/mscorlib/src/System/Globalization/EncodingTable.cs b/src/mscorlib/src/System/Globalization/EncodingTable.cs index 6d9cc3127fba..75ab073116e3 100644 --- a/src/mscorlib/src/System/Globalization/EncodingTable.cs +++ b/src/mscorlib/src/System/Globalization/EncodingTable.cs @@ -11,7 +11,6 @@ using System.Runtime.Versioning; using System.Security; using System.Threading; -using System.Diagnostics.Contracts; namespace System.Globalization { @@ -139,7 +138,6 @@ internal static int GetCodePageFromName(String name) { throw new ArgumentNullException(nameof(name)); } - Contract.EndContractBlock(); Object codePageObj; diff --git a/src/mscorlib/src/System/Globalization/IdnMapping.cs b/src/mscorlib/src/System/Globalization/IdnMapping.cs index 4320e3abf520..176e5feed563 100644 --- a/src/mscorlib/src/System/Globalization/IdnMapping.cs +++ b/src/mscorlib/src/System/Globalization/IdnMapping.cs @@ -25,7 +25,6 @@ // RFC 3492 - Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA) using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Text; namespace System.Globalization @@ -62,7 +61,6 @@ public string GetAscii(string unicode, int index) { if (unicode == null) throw new ArgumentNullException(nameof(unicode)); - Contract.EndContractBlock(); return GetAscii(unicode, index, unicode.Length - index); } @@ -76,7 +74,6 @@ public string GetAscii(string unicode, int index, int count) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); if (index > unicode.Length - count) throw new ArgumentOutOfRangeException(nameof(unicode), SR.ArgumentOutOfRange_IndexCountBuffer); - Contract.EndContractBlock(); if (count == 0) { @@ -111,7 +108,6 @@ public string GetUnicode(string ascii, int index) { if (ascii == null) throw new ArgumentNullException(nameof(ascii)); - Contract.EndContractBlock(); return GetUnicode(ascii, index, ascii.Length - index); } @@ -131,7 +127,6 @@ public string GetUnicode(string ascii, int index, int count) // The Win32 APIs fail on an embedded null, but not on a terminating null. if (count > 0 && ascii[index + count - 1] == (char)0) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); - Contract.EndContractBlock(); if (GlobalizationMode.Invariant) { @@ -328,7 +323,7 @@ static string PunycodeEncode(string unicode) { // Find end of this segment iNextDot = unicode.IndexOfAny(c_Dots, iAfterLastDot); - Contract.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken"); + Debug.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken"); if (iNextDot < 0) iNextDot = unicode.Length; @@ -469,7 +464,7 @@ static string PunycodeEncode(string unicode) if (test < n) { delta++; - Contract.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int"); + Debug.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int"); } if (test == n) diff --git a/src/mscorlib/src/System/Globalization/RegionInfo.cs b/src/mscorlib/src/System/Globalization/RegionInfo.cs index ab52002fdcdf..3acfa160b986 100644 --- a/src/mscorlib/src/System/Globalization/RegionInfo.cs +++ b/src/mscorlib/src/System/Globalization/RegionInfo.cs @@ -15,7 +15,6 @@ //////////////////////////////////////////////////////////////////////////// using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System.Globalization @@ -66,7 +65,6 @@ public RegionInfo(String name) throw new ArgumentException(SR.Argument_NoRegionInvariantCulture, nameof(name)); } - Contract.EndContractBlock(); // // For CoreCLR we only want the region names that are full culture names diff --git a/src/mscorlib/src/System/Globalization/TextInfo.Unix.cs b/src/mscorlib/src/System/Globalization/TextInfo.Unix.cs index 9f80d73891e7..27b35da284cc 100644 --- a/src/mscorlib/src/System/Globalization/TextInfo.Unix.cs +++ b/src/mscorlib/src/System/Globalization/TextInfo.Unix.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Security; using System.Text; diff --git a/src/mscorlib/src/System/Globalization/TextInfo.cs b/src/mscorlib/src/System/Globalization/TextInfo.cs index c5acbd457986..70475af59ec1 100644 --- a/src/mscorlib/src/System/Globalization/TextInfo.cs +++ b/src/mscorlib/src/System/Globalization/TextInfo.cs @@ -13,7 +13,6 @@ //////////////////////////////////////////////////////////////////////////// using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.Serialization; using System.Text; @@ -221,7 +220,6 @@ public virtual object Clone() public static TextInfo ReadOnly(TextInfo textInfo) { if (textInfo == null) { throw new ArgumentNullException(nameof(textInfo)); } - Contract.EndContractBlock(); if (textInfo.IsReadOnly) { return (textInfo); } TextInfo clonedTextInfo = (TextInfo)(textInfo.MemberwiseClone()); @@ -541,7 +539,6 @@ public unsafe String ToTitleCase(String str) { throw new ArgumentNullException(nameof(str)); } - Contract.EndContractBlock(); if (str.Length == 0) { return (str); diff --git a/src/mscorlib/src/System/Guid.CoreCLR.cs b/src/mscorlib/src/System/Guid.CoreCLR.cs index f71d71b14514..e3722b80929b 100644 --- a/src/mscorlib/src/System/Guid.CoreCLR.cs +++ b/src/mscorlib/src/System/Guid.CoreCLR.cs @@ -4,21 +4,13 @@ using Microsoft.Win32; using System.Runtime.InteropServices; -using System.Diagnostics.Contracts; namespace System { partial struct Guid { - // This will create a new guid. Since we've now decided that constructors should 0-init, - // we need a method that allows users to create a guid. public static Guid NewGuid() { - // CoCreateGuid should never return Guid.Empty, since it attempts to maintain some - // uniqueness guarantees. It should also never return a known GUID, but it's unclear - // how extensively it checks for known values. - Contract.Ensures(Contract.Result() != Guid.Empty); - Guid guid; Marshal.ThrowExceptionForHR(Win32Native.CoCreateGuid(out guid), new IntPtr(-1)); return guid; diff --git a/src/mscorlib/src/System/IO/BinaryReader.cs b/src/mscorlib/src/System/IO/BinaryReader.cs index 83fc2806bf55..33ff5fa5030f 100644 --- a/src/mscorlib/src/System/IO/BinaryReader.cs +++ b/src/mscorlib/src/System/IO/BinaryReader.cs @@ -19,7 +19,6 @@ using System.Text; using System.Globalization; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Security; namespace System.IO @@ -61,7 +60,6 @@ public BinaryReader(Stream input, Encoding encoding, bool leaveOpen) } if (!input.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable); - Contract.EndContractBlock(); _stream = input; _decoder = encoding.GetDecoder(); _maxCharsSize = encoding.GetMaxCharCount(MaxCharBytesSize); @@ -119,8 +117,6 @@ public void Dispose() public virtual int PeekChar() { - Contract.Ensures(Contract.Result() >= -1); - if (_stream == null) __Error.FileNotOpen(); if (!_stream.CanSeek) @@ -133,8 +129,6 @@ public virtual int PeekChar() public virtual int Read() { - Contract.Ensures(Contract.Result() >= -1); - if (_stream == null) { __Error.FileNotOpen(); @@ -270,8 +264,6 @@ public virtual decimal ReadDecimal() public virtual String ReadString() { - Contract.Ensures(Contract.Result() != null); - if (_stream == null) __Error.FileNotOpen(); @@ -346,9 +338,6 @@ public virtual int Read(char[] buffer, int index, int count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } - Contract.Ensures(Contract.Result() >= 0); - Contract.Ensures(Contract.Result() <= count); - Contract.EndContractBlock(); if (_stream == null) __Error.FileNotOpen(); @@ -359,10 +348,6 @@ public virtual int Read(char[] buffer, int index, int count) public virtual int Read(Span destination) { - Contract.Ensures(Contract.Result() >= 0); - Contract.Ensures(Contract.Result() <= destination.Length); - Contract.EndContractBlock(); - if (_stream == null) __Error.FileNotOpen(); @@ -537,9 +522,6 @@ public virtual char[] ReadChars(int count) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(Contract.Result().Length <= count); - Contract.EndContractBlock(); if (_stream == null) { __Error.FileNotOpen(); @@ -573,9 +555,6 @@ public virtual int Read(byte[] buffer, int index, int count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.Ensures(Contract.Result() >= 0); - Contract.Ensures(Contract.Result() <= count); - Contract.EndContractBlock(); if (_stream == null) __Error.FileNotOpen(); return _stream.Read(buffer, index, count); @@ -583,10 +562,6 @@ public virtual int Read(byte[] buffer, int index, int count) public virtual int Read(Span destination) { - Contract.Ensures(Contract.Result() >= 0); - Contract.Ensures(Contract.Result() <= destination.Length); - Contract.EndContractBlock(); - if (_stream == null) __Error.FileNotOpen(); @@ -596,9 +571,6 @@ public virtual int Read(Span destination) public virtual byte[] ReadBytes(int count) { if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(Contract.Result().Length <= Contract.OldValue(count)); - Contract.EndContractBlock(); if (_stream == null) __Error.FileNotOpen(); if (count == 0) diff --git a/src/mscorlib/src/System/IO/Directory.cs b/src/mscorlib/src/System/IO/Directory.cs index fcc43f73c428..bb0502287837 100644 --- a/src/mscorlib/src/System/IO/Directory.cs +++ b/src/mscorlib/src/System/IO/Directory.cs @@ -21,7 +21,6 @@ using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.IO { @@ -33,9 +32,9 @@ internal sealed class SearchData { public SearchData(String fullPath, String userPath, SearchOption searchOption) { - Contract.Requires(fullPath != null && fullPath.Length > 0); - Contract.Requires(userPath != null && userPath.Length > 0); - Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); + Debug.Assert(fullPath != null && fullPath.Length > 0); + Debug.Assert(userPath != null && userPath.Length > 0); + Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); this.fullPath = fullPath; this.userPath = userPath; @@ -56,18 +55,15 @@ public static IEnumerable EnumerateFiles(String path, String searchPatte throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); - Contract.Ensures(Contract.Result>() != null); - Contract.EndContractBlock(); return InternalEnumerateFiles(path, searchPattern, searchOption); } private static IEnumerable InternalEnumerateFiles(String path, String searchPattern, SearchOption searchOption) { - Contract.Requires(path != null); - Contract.Requires(searchPattern != null); - Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); - Contract.Ensures(Contract.Result>() != null); + Debug.Assert(path != null); + Debug.Assert(searchPattern != null); + Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return EnumerateFileSystemNames(path, searchPattern, searchOption, true, false); } @@ -75,10 +71,9 @@ private static IEnumerable InternalEnumerateFiles(String path, String se private static IEnumerable EnumerateFileSystemNames(String path, String searchPattern, SearchOption searchOption, bool includeFiles, bool includeDirs) { - Contract.Requires(path != null); - Contract.Requires(searchPattern != null); - Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); - Contract.Ensures(Contract.Result>() != null); + Debug.Assert(path != null); + Debug.Assert(searchPattern != null); + Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return FileSystemEnumerableFactory.CreateFileNameIterator(path, path, searchPattern, includeFiles, includeDirs, searchOption, true); diff --git a/src/mscorlib/src/System/IO/File.cs b/src/mscorlib/src/System/IO/File.cs index e34b7aedabe3..b393feac3f90 100644 --- a/src/mscorlib/src/System/IO/File.cs +++ b/src/mscorlib/src/System/IO/File.cs @@ -21,7 +21,6 @@ using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.IO { @@ -115,16 +114,15 @@ public static String[] ReadAllLines(String path) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath); - Contract.EndContractBlock(); return InternalReadAllLines(path, Encoding.UTF8); } private static String[] InternalReadAllLines(String path, Encoding encoding) { - Contract.Requires(path != null); - Contract.Requires(encoding != null); - Contract.Requires(path.Length != 0); + Debug.Assert(path != null); + Debug.Assert(encoding != null); + Debug.Assert(path.Length != 0); String line; List lines = new List(); diff --git a/src/mscorlib/src/System/IO/FileSystemEnumerable.cs b/src/mscorlib/src/System/IO/FileSystemEnumerable.cs index a16aad25c1dc..9e52d255cc27 100644 --- a/src/mscorlib/src/System/IO/FileSystemEnumerable.cs +++ b/src/mscorlib/src/System/IO/FileSystemEnumerable.cs @@ -20,7 +20,6 @@ using System.Globalization; using System.Runtime.Versioning; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Threading; namespace System.IO @@ -34,9 +33,9 @@ internal static class FileSystemEnumerableFactory internal static IEnumerable CreateFileNameIterator(String path, String originalUserPath, String searchPattern, bool includeFiles, bool includeDirs, SearchOption searchOption, bool checkHost) { - Contract.Requires(path != null); - Contract.Requires(originalUserPath != null); - Contract.Requires(searchPattern != null); + Debug.Assert(path != null); + Debug.Assert(originalUserPath != null); + Debug.Assert(searchPattern != null); SearchResultHandler handler = new StringResultHandler(includeFiles, includeDirs); return new FileSystemEnumerableIterator(path, originalUserPath, searchPattern, searchOption, handler, checkHost); @@ -152,11 +151,11 @@ internal class FileSystemEnumerableIterator : Iterator #endif internal FileSystemEnumerableIterator(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler resultHandler, bool checkHost) { - Contract.Requires(path != null); - Contract.Requires(originalUserPath != null); - Contract.Requires(searchPattern != null); - Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); - Contract.Requires(resultHandler != null); + Debug.Assert(path != null); + Debug.Assert(originalUserPath != null); + Debug.Assert(searchPattern != null); + Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); + Debug.Assert(resultHandler != null); #if !PLATFORM_UNIX _setBackOldMode = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out _oldMode); @@ -438,7 +437,7 @@ private void HandleError(int hr, String path) private void AddSearchableDirsToStack(Directory.SearchData localSearchData) { - Contract.Requires(localSearchData != null); + Debug.Assert(localSearchData != null); String searchPath = Path.Combine(localSearchData.fullPath, "*"); SafeFindHandle hnd = null; @@ -494,7 +493,7 @@ private void AddSearchableDirsToStack(Directory.SearchData localSearchData) private static String NormalizeSearchPattern(String searchPattern) { - Contract.Requires(searchPattern != null); + Debug.Assert(searchPattern != null); // Make this corner case more useful, like dir if (searchPattern.Equals(".")) @@ -508,9 +507,9 @@ private static String NormalizeSearchPattern(String searchPattern) private static String GetNormalizedSearchCriteria(String fullSearchString, String fullPathMod) { - Contract.Requires(fullSearchString != null); - Contract.Requires(fullPathMod != null); - Contract.Requires(fullSearchString.Length >= fullPathMod.Length); + Debug.Assert(fullSearchString != null); + Debug.Assert(fullPathMod != null); + Debug.Assert(fullSearchString.Length >= fullPathMod.Length); String searchCriteria = null; char lastChar = fullPathMod[fullPathMod.Length - 1]; @@ -529,8 +528,8 @@ private static String GetNormalizedSearchCriteria(String fullSearchString, Strin private static String GetFullSearchString(String fullPath, String searchPattern) { - Contract.Requires(fullPath != null); - Contract.Requires(searchPattern != null); + Debug.Assert(fullPath != null); + Debug.Assert(searchPattern != null); String tempStr = Path.Combine(fullPath, searchPattern); @@ -547,7 +546,6 @@ private static String GetFullSearchString(String fullPath, String searchPattern) internal abstract class SearchResultHandler { - internal abstract bool IsResultIncluded(SearchResult result); internal abstract TSource CreateObject(SearchResult result); @@ -587,8 +585,8 @@ internal sealed class SearchResult internal SearchResult(String fullPath, String userPath, Win32Native.WIN32_FIND_DATA findData) { - Contract.Requires(fullPath != null); - Contract.Requires(userPath != null); + Debug.Assert(fullPath != null); + Debug.Assert(userPath != null); this.fullPath = fullPath; this.userPath = userPath; diff --git a/src/mscorlib/src/System/IO/MemoryStream.cs b/src/mscorlib/src/System/IO/MemoryStream.cs index 7d9ac901c0cf..330efcc1e7fa 100644 --- a/src/mscorlib/src/System/IO/MemoryStream.cs +++ b/src/mscorlib/src/System/IO/MemoryStream.cs @@ -20,7 +20,6 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; @@ -39,7 +38,6 @@ public class MemoryStream : Stream private byte[] _buffer; // Either allocated internally or externally. private int _origin; // For user-provided arrays, start at this origin private int _position; // read/write head. - [ContractPublicPropertyName("Length")] private int _length; // Number of bytes within the memory stream private int _capacity; // length of usable portion of buffer for stream // Note that _capacity == _buffer.Length for non-user-provided byte[]'s @@ -64,7 +62,6 @@ public MemoryStream(int capacity) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity); } - Contract.EndContractBlock(); _buffer = capacity != 0 ? new byte[capacity] : Array.Empty(); _capacity = capacity; @@ -83,7 +80,6 @@ public MemoryStream(byte[] buffer) public MemoryStream(byte[] buffer, bool writable) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); - Contract.EndContractBlock(); _buffer = buffer; _length = _capacity = buffer.Length; _writable = writable; @@ -112,7 +108,6 @@ public MemoryStream(byte[] buffer, int index, int count, bool writable, bool pub throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.EndContractBlock(); _buffer = buffer; _origin = _position = index; @@ -125,19 +120,16 @@ public MemoryStream(byte[] buffer, int index, int count, bool writable, bool pub public override bool CanRead { - [Pure] get { return _isOpen; } } public override bool CanSeek { - [Pure] get { return _isOpen; } } public override bool CanWrite { - [Pure] get { return _writable; } } @@ -301,8 +293,6 @@ public virtual int Capacity // Only update the capacity if the MS is expandable and the value is different than the current capacity. // Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity if (value < Length) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity); - Contract.Ensures(_capacity - _origin == value); - Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); if (!_expandable && (value != Capacity)) __Error.MemoryStreamNotExpandable(); @@ -345,8 +335,6 @@ public override long Position { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.Ensures(Position == value); - Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); @@ -366,7 +354,6 @@ public override int Read([In, Out] byte[] buffer, int offset, int count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); @@ -431,7 +418,6 @@ public override Task ReadAsync(Byte[] buffer, int offset, int count, Cancel throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.EndContractBlock(); // contract validation copied from Read(...) // If cancellation was requested, bail early if (cancellationToken.IsCancellationRequested) @@ -629,8 +615,6 @@ public override void SetLength(long value) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); } - Contract.Ensures(_length - _origin == value); - Contract.EndContractBlock(); EnsureWriteable(); // Origin wasn't publicly exposed above. @@ -666,7 +650,6 @@ public override void Write(byte[] buffer, int offset, int count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); EnsureWriteable(); @@ -756,7 +739,6 @@ public override Task WriteAsync(Byte[] buffer, int offset, int count, Cancellati throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.EndContractBlock(); // contract validation copied from Write(...) // If cancellation is already requested, bail early if (cancellationToken.IsCancellationRequested) @@ -835,7 +817,6 @@ public virtual void WriteTo(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream); - Contract.EndContractBlock(); if (!_isOpen) __Error.StreamIsClosed(); stream.Write(_buffer, _origin, _length - _origin); diff --git a/src/mscorlib/src/System/IO/Stream.cs b/src/mscorlib/src/System/IO/Stream.cs index 82fad24c6da3..83f327b70bd7 100644 --- a/src/mscorlib/src/System/IO/Stream.cs +++ b/src/mscorlib/src/System/IO/Stream.cs @@ -25,7 +25,6 @@ using System.Runtime.ExceptionServices; using System.Security; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Reflection; namespace System.IO @@ -53,20 +52,17 @@ internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() public abstract bool CanRead { - [Pure] get; } // If CanSeek is false, Position, Seek, Length, and SetLength should throw. public abstract bool CanSeek { - [Pure] get; } public virtual bool CanTimeout { - [Pure] get { return false; @@ -75,7 +71,6 @@ public virtual bool CanTimeout public abstract bool CanWrite { - [Pure] get; } @@ -94,7 +89,6 @@ public virtual int ReadTimeout { get { - Contract.Ensures(Contract.Result() >= 0); throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } set @@ -107,7 +101,6 @@ public virtual int WriteTimeout { get { - Contract.Ensures(Contract.Result() >= 0); throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } set @@ -166,10 +159,10 @@ public virtual Task CopyToAsync(Stream destination, Int32 bufferSize, Cancellati private async Task CopyToAsyncInternal(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) { - Contract.Requires(destination != null); - Contract.Requires(bufferSize > 0); - Contract.Requires(CanRead); - Contract.Requires(destination.CanWrite); + Debug.Assert(destination != null); + Debug.Assert(bufferSize > 0); + Debug.Assert(CanRead); + Debug.Assert(destination.CanWrite); byte[] buffer = ArrayPool.Shared.Rent(bufferSize); bufferSize = 0; // reuse same field for high water mark to avoid needing another field in the state machine @@ -251,11 +244,8 @@ public virtual void CopyTo(Stream destination, int bufferSize) // should put their cleanup starting in V2. public virtual void Close() { - /* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully. - Contract.Ensures(CanRead == false); - Contract.Ensures(CanWrite == false); - Contract.Ensures(CanSeek == false); - */ + // Ideally we would assert CanRead == CanWrite == CanSeek = false, + // but we'd have to fix PipeStream & NetworkStream very carefully. Dispose(true); GC.SuppressFinalize(this); @@ -263,11 +253,8 @@ public virtual void Close() public void Dispose() { - /* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully. - Contract.Ensures(CanRead == false); - Contract.Ensures(CanWrite == false); - Contract.Ensures(CanSeek == false); - */ + // Ideally we would assert CanRead == CanWrite == CanSeek = false, + // but we'd have to fix PipeStream & NetworkStream very carefully. Close(); } @@ -296,13 +283,11 @@ public virtual Task FlushAsync(CancellationToken cancellationToken) [Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")] protected virtual WaitHandle CreateWaitHandle() { - Contract.Ensures(Contract.Result() != null); return new ManualResetEvent(false); } public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { - Contract.Ensures(Contract.Result() != null); return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true); } @@ -310,7 +295,6 @@ internal IAsyncResult BeginReadInternal( byte[] buffer, int offset, int count, AsyncCallback callback, Object state, bool serializeAsynchronously, bool apm) { - Contract.Ensures(Contract.Result() != null); if (!CanRead) __Error.ReadNotSupported(); // To avoid a race with a stream's position pointer & generating race conditions @@ -372,8 +356,6 @@ public virtual int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); - Contract.Ensures(Contract.Result() >= 0); - Contract.EndContractBlock(); var readTask = _activeReadWriteTask; @@ -471,7 +453,6 @@ private Task BeginEndReadAsync(Byte[] buffer, Int32 offset, Int32 count) public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { - Contract.Ensures(Contract.Result() != null); return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true); } @@ -479,7 +460,6 @@ internal IAsyncResult BeginWriteInternal( byte[] buffer, int offset, int count, AsyncCallback callback, Object state, bool serializeAsynchronously, bool apm) { - Contract.Ensures(Contract.Result() != null); if (!CanWrite) __Error.WriteNotSupported(); // To avoid a race condition with a stream's position pointer & generating conditions @@ -539,9 +519,8 @@ internal IAsyncResult BeginWriteInternal( private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask) { - Debug.Assert(readWriteTask != null); // Should be Contract.Requires, but CCRewrite is doing a poor job with - // preconditions in async methods that await. - Debug.Assert(asyncWaiter != null); // Ditto + Debug.Assert(readWriteTask != null); + Debug.Assert(asyncWaiter != null); // If the wait has already completed, run the task. if (asyncWaiter.IsCompleted) @@ -562,7 +541,7 @@ private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWrite private void RunReadWriteTask(ReadWriteTask readWriteTask) { - Contract.Requires(readWriteTask != null); + Debug.Assert(readWriteTask != null); Debug.Assert(_activeReadWriteTask == null, "Expected no other readers or writers"); // Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race. @@ -585,7 +564,6 @@ public virtual void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); - Contract.EndContractBlock(); var writeTask = _activeReadWriteTask; if (writeTask == null) @@ -652,10 +630,9 @@ public ReadWriteTask( Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback) : base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach) { - Contract.Requires(function != null); - Contract.Requires(stream != null); - Contract.Requires(buffer != null); - Contract.EndContractBlock(); + Debug.Assert(function != null); + Debug.Assert(stream != null); + Debug.Assert(buffer != null); // Store the arguments _isRead = isRead; @@ -807,9 +784,6 @@ public virtual int Read(Span destination) // significantly for people who are reading one byte at a time. public virtual int ReadByte() { - Contract.Ensures(Contract.Result() >= -1); - Contract.Ensures(Contract.Result() < 256); - byte[] oneByteArray = new byte[1]; int r = Read(oneByteArray, 0, 1); if (r == 0) @@ -846,8 +820,6 @@ public static Stream Synchronized(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); if (stream is SyncStream) return stream; @@ -861,8 +833,6 @@ protected virtual void ObjectInvariant() internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { - Contract.Ensures(Contract.Result() != null); - // To avoid a race with a stream's position pointer & generating conditions // with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple @@ -890,15 +860,11 @@ internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, As internal static int BlockingEndRead(IAsyncResult asyncResult) { - Contract.Ensures(Contract.Result() >= 0); - return SynchronousAsyncResult.EndRead(asyncResult); } internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { - Contract.Ensures(Contract.Result() != null); - // To avoid a race condition with a stream's position pointer & generating conditions // with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple @@ -935,19 +901,16 @@ internal NullStream() { } public override bool CanRead { - [Pure] get { return true; } } public override bool CanWrite { - [Pure] get { return true; } } public override bool CanSeek { - [Pure] get { return true; } } @@ -1007,7 +970,6 @@ public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); - Contract.EndContractBlock(); return BlockingEndRead(asyncResult); } @@ -1023,7 +985,6 @@ public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); - Contract.EndContractBlock(); BlockingEndWrite(asyncResult); } @@ -1192,31 +1153,26 @@ internal SyncStream(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); - Contract.EndContractBlock(); _stream = stream; } public override bool CanRead { - [Pure] get { return _stream.CanRead; } } public override bool CanWrite { - [Pure] get { return _stream.CanWrite; } } public override bool CanSeek { - [Pure] get { return _stream.CanSeek; } } public override bool CanTimeout { - [Pure] get { return _stream.CanTimeout; @@ -1356,8 +1312,6 @@ public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); - Contract.Ensures(Contract.Result() >= 0); - Contract.EndContractBlock(); lock (_stream) return _stream.EndRead(asyncResult); @@ -1415,7 +1369,6 @@ public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); - Contract.EndContractBlock(); lock (_stream) _stream.EndWrite(asyncResult); diff --git a/src/mscorlib/src/System/IO/StreamReader.cs b/src/mscorlib/src/System/IO/StreamReader.cs index 9ff91876634e..092bf69bc5f2 100644 --- a/src/mscorlib/src/System/IO/StreamReader.cs +++ b/src/mscorlib/src/System/IO/StreamReader.cs @@ -7,7 +7,6 @@ using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.Contracts; using System.Threading.Tasks; namespace System.IO @@ -148,7 +147,6 @@ public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByt throw new ArgumentException(SR.Argument_StreamNotReadable); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); - Contract.EndContractBlock(); Init(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, leaveOpen); } @@ -180,7 +178,6 @@ public StreamReader(String path, Encoding encoding, bool detectEncodingFromByteO throw new ArgumentException(SR.Argument_EmptyPath); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); - Contract.EndContractBlock(); Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.SequentialScan); Init(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, false); @@ -303,7 +300,6 @@ public bool EndOfStream { } } - [Pure] public override int Peek() { if (stream == null) __Error.ReaderClosed(); @@ -339,7 +335,6 @@ public override int Read([In, Out] char[] buffer, int index, int count) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.EndContractBlock(); if (stream == null) __Error.ReaderClosed(); @@ -397,7 +392,6 @@ public override int ReadBlock([In, Out] char[] buffer, int index, int count) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.EndContractBlock(); if (stream == null) __Error.ReaderClosed(); @@ -873,7 +867,6 @@ public override Task ReadAsync(char[] buffer, int index, int count) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.EndContractBlock(); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Read() which a subclass might have overriden. @@ -1059,7 +1052,6 @@ public override Task ReadBlockAsync(char[] buffer, int index, int count) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.EndContractBlock(); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Read() which a subclass might have overriden. @@ -1173,7 +1165,6 @@ public override int Read() return -1; } - [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override int Read(char[] buffer, int index, int count) { return 0; } diff --git a/src/mscorlib/src/System/IO/TextReader.cs b/src/mscorlib/src/System/IO/TextReader.cs index 2531778d6d95..9ef4f9fd0ca5 100644 --- a/src/mscorlib/src/System/IO/TextReader.cs +++ b/src/mscorlib/src/System/IO/TextReader.cs @@ -17,8 +17,8 @@ using System.Text; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; @@ -31,7 +31,6 @@ namespace System.IO { // This class is intended for character input, not bytes. // There are methods on the Stream class for reading bytes. internal abstract class TextReader : MarshalByRefObject, IDisposable { - public static readonly TextReader Null = new NullTextReader(); protected TextReader() {} @@ -65,11 +64,8 @@ protected virtual void Dispose(bool disposing) // // This default method simply returns -1. // - [Pure] public virtual int Peek() { - Contract.Ensures(Contract.Result() >= -1); - return -1; } @@ -80,7 +76,6 @@ public virtual int Peek() // public virtual int Read() { - Contract.Ensures(Contract.Result() >= -1); return -1; } @@ -99,9 +94,6 @@ public virtual int Read([In, Out] char[] buffer, int index, int count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.Ensures(Contract.Result() >= 0); - Contract.Ensures(Contract.Result() <= Contract.OldValue(count)); - Contract.EndContractBlock(); int n = 0; do { @@ -116,8 +108,6 @@ public virtual int Read([In, Out] char[] buffer, int index, int count) // TextReader, and returns them as one string. public virtual String ReadToEnd() { - Contract.Ensures(Contract.Result() != null); - char[] chars = new char[4096]; int len; StringBuilder sb = new StringBuilder(4096); @@ -133,9 +123,6 @@ public virtual String ReadToEnd() // public virtual int ReadBlock([In, Out] char[] buffer, int index, int count) { - Contract.Ensures(Contract.Result() >= 0); - Contract.Ensures(Contract.Result() <= count); - int i, n = 0; do { n += (i = Read(buffer, index + n, count - n)); @@ -196,17 +183,16 @@ public virtual Task ReadAsync(char[] buffer, int index, int count) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.EndContractBlock(); return ReadAsyncInternal(buffer, index, count); } internal virtual Task ReadAsyncInternal(char[] buffer, int index, int count) { - Contract.Requires(buffer != null); - Contract.Requires(index >= 0); - Contract.Requires(count >= 0); - Contract.Requires(buffer.Length - index >= count); + Debug.Assert(buffer != null); + Debug.Assert(index >= 0); + Debug.Assert(count >= 0); + Debug.Assert(buffer.Length - index >= count); var tuple = new Tuple(this, buffer, index, count); return Task.Factory.StartNew(state => @@ -226,17 +212,16 @@ public virtual Task ReadBlockAsync(char[] buffer, int index, int count) if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.EndContractBlock(); return ReadBlockAsyncInternal(buffer, index, count); } private async Task ReadBlockAsyncInternal(char[] buffer, int index, int count) { - Contract.Requires(buffer != null); - Contract.Requires(index >= 0); - Contract.Requires(count >= 0); - Contract.Requires(buffer.Length - index >= count); + Debug.Assert(buffer != null); + Debug.Assert(index >= 0); + Debug.Assert(count >= 0); + Debug.Assert(buffer.Length - index >= count); int i, n = 0; do @@ -253,8 +238,6 @@ public static TextReader Synchronized(TextReader reader) { if (reader==null) throw new ArgumentNullException(nameof(reader)); - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); if (reader is SyncTextReader) return reader; @@ -266,7 +249,6 @@ private sealed class NullTextReader : TextReader { public NullTextReader(){} - [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override int Read(char[] buffer, int index, int count) { return 0; @@ -314,7 +296,6 @@ public override int Read() return _in.Read(); } - [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. [MethodImplAttribute(MethodImplOptions.Synchronized)] public override int Read([In, Out] char[] buffer, int index, int count) { @@ -365,7 +346,6 @@ public override Task ReadBlockAsync(char[] buffer, int index, int count) if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.EndContractBlock(); return Task.FromResult(ReadBlock(buffer, index, count)); } @@ -379,7 +359,6 @@ public override Task ReadAsync(char[] buffer, int index, int count) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.EndContractBlock(); return Task.FromResult(Read(buffer, index, count)); } diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs b/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs index 5f6f588cbed7..43f286919bf7 100644 --- a/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs +++ b/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs @@ -20,7 +20,6 @@ using System.Runtime.Versioning; using Microsoft.Win32.SafeHandles; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.IO { @@ -31,7 +30,6 @@ public class UnmanagedMemoryAccessor : IDisposable { private SafeBuffer _buffer; private Int64 _offset; - [ContractPublicPropertyName("Capacity")] private Int64 _capacity; private FileAccess _access; private bool _isOpen; @@ -79,7 +77,6 @@ protected void Initialize(SafeBuffer buffer, Int64 offset, Int64 capacity, FileA { throw new ArgumentOutOfRangeException(nameof(access)); } - Contract.EndContractBlock(); if (_isOpen) { @@ -504,7 +501,6 @@ public void Read(Int64 position, out T structure) where T : struct { throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum); } - Contract.EndContractBlock(); if (!_isOpen) { @@ -555,7 +551,6 @@ public int ReadArray(Int64 position, T[] array, Int32 offset, Int32 count) wh { throw new ArgumentException(SR.Argument_OffsetAndLengthOutOfBounds); } - Contract.EndContractBlock(); if (!CanRead) { if (!_isOpen) @@ -905,7 +900,6 @@ public void Write(Int64 position, ref T structure) where T : struct { throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum); } - Contract.EndContractBlock(); if (!_isOpen) { @@ -961,7 +955,6 @@ public void WriteArray(Int64 position, T[] array, Int32 offset, Int32 count) { throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired); } - Contract.EndContractBlock(); if (!_isOpen) { @@ -1041,7 +1034,6 @@ private void EnsureSafeToRead(Int64 position, int sizeOfType) { throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum); } - Contract.EndContractBlock(); if (position > _capacity - sizeOfType) { if (position >= _capacity) @@ -1069,7 +1061,6 @@ private void EnsureSafeToWrite(Int64 position, int sizeOfType) { throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum); } - Contract.EndContractBlock(); if (position > _capacity - sizeOfType) { if (position >= _capacity) diff --git a/src/mscorlib/src/System/IO/__Error.cs b/src/mscorlib/src/System/IO/__Error.cs index 6af1fcfadca9..ea58db37a88c 100644 --- a/src/mscorlib/src/System/IO/__Error.cs +++ b/src/mscorlib/src/System/IO/__Error.cs @@ -21,11 +21,9 @@ using System.Text; using System.Globalization; using System.Security; -using System.Diagnostics.Contracts; namespace System.IO { - [Pure] internal static class __Error { internal static void EndOfFile() diff --git a/src/mscorlib/src/System/IntPtr.cs b/src/mscorlib/src/System/IntPtr.cs index e3439801ff6d..76a8ea92d92c 100644 --- a/src/mscorlib/src/System/IntPtr.cs +++ b/src/mscorlib/src/System/IntPtr.cs @@ -20,7 +20,6 @@ namespace System using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Security; - using System.Diagnostics.Contracts; [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] @@ -31,7 +30,6 @@ public struct IntPtr : IEquatable, ISerializable public static readonly IntPtr Zero; // fast way to compare IntPtr to (IntPtr)0 while IntPtr.Zero doesn't work due to slow statics access - [Pure] internal unsafe bool IsNull() { return (_value == null); @@ -82,7 +80,6 @@ unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext { throw new ArgumentNullException(nameof(info)); } - Contract.EndContractBlock(); #if BIT64 info.AddValue("value", (long)(_value)); #else // !BIT64 (32) @@ -146,8 +143,6 @@ public unsafe override String ToString() public unsafe String ToString(String format) { - Contract.Ensures(Contract.Result() != null); - #if BIT64 return ((long)_value).ToString(format, CultureInfo.InvariantCulture); #else // !BIT64 (32) @@ -249,7 +244,6 @@ public static IntPtr Subtract(IntPtr pointer, int offset) public static int Size { - [Pure] [System.Runtime.Versioning.NonVersionable] get { diff --git a/src/mscorlib/src/System/MissingMemberException.cs b/src/mscorlib/src/System/MissingMemberException.cs index def3c39824bd..44ceaaf1e194 100644 --- a/src/mscorlib/src/System/MissingMemberException.cs +++ b/src/mscorlib/src/System/MissingMemberException.cs @@ -17,7 +17,6 @@ using System.Runtime.CompilerServices; using System.Globalization; using System.Runtime.Versioning; -using System.Diagnostics.Contracts; namespace System { diff --git a/src/mscorlib/src/System/MulticastDelegate.cs b/src/mscorlib/src/System/MulticastDelegate.cs index 8a5d3e514089..0ab8ef80e73e 100644 --- a/src/mscorlib/src/System/MulticastDelegate.cs +++ b/src/mscorlib/src/System/MulticastDelegate.cs @@ -8,7 +8,6 @@ using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Reflection.Emit; namespace System @@ -410,8 +409,6 @@ protected override sealed Delegate RemoveImpl(Delegate value) // This method returns the Invocation list of this multicast delegate. public override sealed Delegate[] GetInvocationList() { - Contract.Ensures(Contract.Result() != null); - Delegate[] del; Object[] invocationList = _invocationList as Object[]; if (invocationList == null) diff --git a/src/mscorlib/src/System/Nullable.cs b/src/mscorlib/src/System/Nullable.cs index a2c7c350c9c5..f9ee9acdc70b 100644 --- a/src/mscorlib/src/System/Nullable.cs +++ b/src/mscorlib/src/System/Nullable.cs @@ -11,7 +11,6 @@ using System.Runtime; using System.Runtime.CompilerServices; using System.Security; -using System.Diagnostics.Contracts; namespace System { @@ -147,7 +146,6 @@ public static Type GetUnderlyingType(Type nullableType) { throw new ArgumentNullException(nameof(nullableType)); } - Contract.EndContractBlock(); Type result = null; if (nullableType.IsGenericType && !nullableType.IsGenericTypeDefinition) { diff --git a/src/mscorlib/src/System/Number.cs b/src/mscorlib/src/System/Number.cs index 0eaa0b22851d..3e581ac06dea 100644 --- a/src/mscorlib/src/System/Number.cs +++ b/src/mscorlib/src/System/Number.cs @@ -11,7 +11,6 @@ using System.Security; using System.Text; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System { diff --git a/src/mscorlib/src/System/Object.cs b/src/mscorlib/src/System/Object.cs index 8df1caa9e521..8d74aaeed05d 100644 --- a/src/mscorlib/src/System/Object.cs +++ b/src/mscorlib/src/System/Object.cs @@ -15,12 +15,12 @@ namespace System { using System; + using System.Diagnostics; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; - using System.Diagnostics.Contracts; using CultureInfo = System.Globalization.CultureInfo; using FieldInfo = System.Reflection.FieldInfo; using BindingFlags = System.Reflection.BindingFlags; @@ -97,7 +97,6 @@ public virtual int GetHashCode() // Returns a Type object which represent this object instance. // - [Pure] [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern Type GetType(); @@ -121,8 +120,8 @@ public virtual int GetHashCode() // private void FieldSetter(String typeName, String fieldName, Object val) { - Contract.Requires(typeName != null); - Contract.Requires(fieldName != null); + Debug.Assert(typeName != null); + Debug.Assert(fieldName != null); // Extract the field info object FieldInfo fldInfo = GetFieldInfo(typeName, fieldName); @@ -151,8 +150,8 @@ private void FieldSetter(String typeName, String fieldName, Object val) // private void FieldGetter(String typeName, String fieldName, ref Object val) { - Contract.Requires(typeName != null); - Contract.Requires(fieldName != null); + Debug.Assert(typeName != null); + Debug.Assert(fieldName != null); // Extract the field info object FieldInfo fldInfo = GetFieldInfo(typeName, fieldName); @@ -165,9 +164,8 @@ private void FieldGetter(String typeName, String fieldName, ref Object val) // private FieldInfo GetFieldInfo(String typeName, String fieldName) { - Contract.Requires(typeName != null); - Contract.Requires(fieldName != null); - Contract.Ensures(Contract.Result() != null); + Debug.Assert(typeName != null); + Debug.Assert(fieldName != null); Type t = GetType(); while (null != t) diff --git a/src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs b/src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs index d437e05e31ee..23b4793964e3 100644 --- a/src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs +++ b/src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs @@ -7,7 +7,6 @@ using System.Configuration.Assemblies; using StackCrawlMark = System.Threading.StackCrawlMark; using System.Runtime.Serialization; -using System.Diagnostics.Contracts; using System.Runtime.Loader; namespace System.Reflection @@ -114,9 +113,6 @@ public static Assembly LoadFrom(String assemblyFile, [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static Assembly Load(String assemblyString) { - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(!Contract.Result().ReflectionOnly); - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeAssembly.InternalLoad(assemblyString, ref stackMark); } @@ -157,9 +153,6 @@ internal static Type GetType_Compat(String assemblyString, String typeName) [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static Assembly Load(AssemblyName assemblyRef) { - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(!Contract.Result().ReflectionOnly); - AssemblyName modifiedAssemblyRef = null; if (assemblyRef != null && assemblyRef.CodeBase != null) { @@ -180,9 +173,6 @@ public static Assembly Load(AssemblyName assemblyRef) [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod internal static Assembly Load(AssemblyName assemblyRef, IntPtr ptrLoadContextBinder) { - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(!Contract.Result().ReflectionOnly); - AssemblyName modifiedAssemblyRef = null; if (assemblyRef != null && assemblyRef.CodeBase != null) { @@ -206,9 +196,6 @@ internal static Assembly Load(AssemblyName assemblyRef, IntPtr ptrLoadContextBin public static Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore) { - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(!Contract.Result().ReflectionOnly); - AppDomain.CheckLoadByteArraySupported(); if (rawAssembly == null) @@ -223,9 +210,6 @@ public static Assembly Load(byte[] rawAssembly, public static Assembly LoadFile(String path) { - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(!Contract.Result().ReflectionOnly); - AppDomain.CheckLoadFileSupported(); Assembly result = null; diff --git a/src/mscorlib/src/System/Reflection/AssemblyName.cs b/src/mscorlib/src/System/Reflection/AssemblyName.cs index fe9a2b1268d1..865a6cfa70da 100644 --- a/src/mscorlib/src/System/Reflection/AssemblyName.cs +++ b/src/mscorlib/src/System/Reflection/AssemblyName.cs @@ -24,7 +24,6 @@ namespace System.Reflection using System.Runtime.Serialization; using System.Runtime.InteropServices; using System.Runtime.Versioning; - using System.Diagnostics.Contracts; using System.Text; public sealed class AssemblyName : ICloneable, ISerializable, IDeserializationCallback @@ -192,7 +191,6 @@ static public AssemblyName GetAssemblyName(String assemblyFile) { if (assemblyFile == null) throw new ArgumentNullException(nameof(assemblyFile)); - Contract.EndContractBlock(); // Assembly.GetNameInternal() will not demand path discovery // permission, so do that first. @@ -310,7 +308,6 @@ public AssemblyName(String assemblyName) { if (assemblyName == null) throw new ArgumentNullException(nameof(assemblyName)); - Contract.EndContractBlock(); if ((assemblyName.Length == 0) || (assemblyName[0] == '\0')) throw new ArgumentException(SR.Format_StringZeroLength); diff --git a/src/mscorlib/src/System/Reflection/Associates.cs b/src/mscorlib/src/System/Reflection/Associates.cs index ed06cb46fc2f..381146bf5e89 100644 --- a/src/mscorlib/src/System/Reflection/Associates.cs +++ b/src/mscorlib/src/System/Reflection/Associates.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Reflection { diff --git a/src/mscorlib/src/System/Reflection/CustomAttribute.cs b/src/mscorlib/src/System/Reflection/CustomAttribute.cs index 1dd88a23a5d1..7f50286996df 100644 --- a/src/mscorlib/src/System/Reflection/CustomAttribute.cs +++ b/src/mscorlib/src/System/Reflection/CustomAttribute.cs @@ -16,7 +16,6 @@ using System.Security; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; -using System.Diagnostics.Contracts; namespace System.Reflection { @@ -35,7 +34,6 @@ public static IList GetCustomAttributes(Module target) { if (target == null) throw new ArgumentNullException(nameof(target)); - Contract.EndContractBlock(); return target.GetCustomAttributesData(); } @@ -44,7 +42,6 @@ public static IList GetCustomAttributes(Assembly target) { if (target == null) throw new ArgumentNullException(nameof(target)); - Contract.EndContractBlock(); return target.GetCustomAttributesData(); } @@ -53,7 +50,6 @@ public static IList GetCustomAttributes(ParameterInfo targe { if (target == null) throw new ArgumentNullException(nameof(target)); - Contract.EndContractBlock(); return target.GetCustomAttributesData(); } @@ -1004,7 +1000,6 @@ internal static void ParseAttributeArguments(ConstArray attributeBlob, { if (customAttributeModule == null) throw new ArgumentNullException(nameof(customAttributeModule)); - Contract.EndContractBlock(); Debug.Assert(customAttributeCtorParameters != null); Debug.Assert(customAttributeNamedParameters != null); @@ -1055,7 +1050,6 @@ public CustomAttributeNamedParameter(string argumentName, CustomAttributeEncodin { if (argumentName == null) throw new ArgumentNullException(nameof(argumentName)); - Contract.EndContractBlock(); m_argumentName = argumentName; m_fieldOrProperty = fieldOrProperty; @@ -1133,7 +1127,7 @@ internal unsafe static class CustomAttribute #region Internal Static Members internal static bool IsDefined(RuntimeType type, RuntimeType caType, bool inherit) { - Contract.Requires(type != null); + Debug.Assert(type != null); if (type.GetElementType() != null) return false; @@ -1162,8 +1156,8 @@ internal static bool IsDefined(RuntimeType type, RuntimeType caType, bool inheri internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType caType, bool inherit) { - Contract.Requires(method != null); - Contract.Requires(caType != null); + Debug.Assert(method != null); + Debug.Assert(caType != null); if (PseudoCustomAttribute.IsDefined(method, caType)) return true; @@ -1189,8 +1183,8 @@ internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType caType, boo internal static bool IsDefined(RuntimeConstructorInfo ctor, RuntimeType caType) { - Contract.Requires(ctor != null); - Contract.Requires(caType != null); + Debug.Assert(ctor != null); + Debug.Assert(caType != null); if (PseudoCustomAttribute.IsDefined(ctor, caType)) return true; @@ -1200,8 +1194,8 @@ internal static bool IsDefined(RuntimeConstructorInfo ctor, RuntimeType caType) internal static bool IsDefined(RuntimePropertyInfo property, RuntimeType caType) { - Contract.Requires(property != null); - Contract.Requires(caType != null); + Debug.Assert(property != null); + Debug.Assert(caType != null); if (PseudoCustomAttribute.IsDefined(property, caType)) return true; @@ -1211,8 +1205,8 @@ internal static bool IsDefined(RuntimePropertyInfo property, RuntimeType caType) internal static bool IsDefined(RuntimeEventInfo e, RuntimeType caType) { - Contract.Requires(e != null); - Contract.Requires(caType != null); + Debug.Assert(e != null); + Debug.Assert(caType != null); if (PseudoCustomAttribute.IsDefined(e, caType)) return true; @@ -1222,8 +1216,8 @@ internal static bool IsDefined(RuntimeEventInfo e, RuntimeType caType) internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType caType) { - Contract.Requires(field != null); - Contract.Requires(caType != null); + Debug.Assert(field != null); + Debug.Assert(caType != null); if (PseudoCustomAttribute.IsDefined(field, caType)) return true; @@ -1233,8 +1227,8 @@ internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType caType) internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType caType) { - Contract.Requires(parameter != null); - Contract.Requires(caType != null); + Debug.Assert(parameter != null); + Debug.Assert(caType != null); if (PseudoCustomAttribute.IsDefined(parameter, caType)) return true; @@ -1244,8 +1238,8 @@ internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType caTyp internal static bool IsDefined(RuntimeAssembly assembly, RuntimeType caType) { - Contract.Requires(assembly != null); - Contract.Requires(caType != null); + Debug.Assert(assembly != null); + Debug.Assert(caType != null); if (PseudoCustomAttribute.IsDefined(assembly, caType)) return true; @@ -1255,8 +1249,8 @@ internal static bool IsDefined(RuntimeAssembly assembly, RuntimeType caType) internal static bool IsDefined(RuntimeModule module, RuntimeType caType) { - Contract.Requires(module != null); - Contract.Requires(caType != null); + Debug.Assert(module != null); + Debug.Assert(caType != null); if (PseudoCustomAttribute.IsDefined(module, caType)) return true; @@ -1266,8 +1260,8 @@ internal static bool IsDefined(RuntimeModule module, RuntimeType caType) internal static Object[] GetCustomAttributes(RuntimeType type, RuntimeType caType, bool inherit) { - Contract.Requires(type != null); - Contract.Requires(caType != null); + Debug.Assert(type != null); + Debug.Assert(caType != null); if (type.GetElementType() != null) return (caType.IsValueType) ? Array.Empty() : CreateAttributeArrayHelper(caType, 0); @@ -1313,8 +1307,8 @@ internal static Object[] GetCustomAttributes(RuntimeType type, RuntimeType caTyp internal static Object[] GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, bool inherit) { - Contract.Requires(method != null); - Contract.Requires(caType != null); + Debug.Assert(method != null); + Debug.Assert(caType != null); if (method.IsGenericMethod && !method.IsGenericMethodDefinition) method = method.GetGenericMethodDefinition() as RuntimeMethodInfo; @@ -1357,8 +1351,8 @@ internal static Object[] GetCustomAttributes(RuntimeMethodInfo method, RuntimeTy internal static Object[] GetCustomAttributes(RuntimeConstructorInfo ctor, RuntimeType caType) { - Contract.Requires(ctor != null); - Contract.Requires(caType != null); + Debug.Assert(ctor != null); + Debug.Assert(caType != null); int pcaCount = 0; Attribute[] pca = PseudoCustomAttribute.GetCustomAttributes(ctor, caType, out pcaCount); @@ -1369,8 +1363,8 @@ internal static Object[] GetCustomAttributes(RuntimeConstructorInfo ctor, Runtim internal static Object[] GetCustomAttributes(RuntimePropertyInfo property, RuntimeType caType) { - Contract.Requires(property != null); - Contract.Requires(caType != null); + Debug.Assert(property != null); + Debug.Assert(caType != null); int pcaCount = 0; Attribute[] pca = PseudoCustomAttribute.GetCustomAttributes(property, caType, out pcaCount); @@ -1382,8 +1376,8 @@ internal static Object[] GetCustomAttributes(RuntimePropertyInfo property, Runti internal static Object[] GetCustomAttributes(RuntimeEventInfo e, RuntimeType caType) { - Contract.Requires(e != null); - Contract.Requires(caType != null); + Debug.Assert(e != null); + Debug.Assert(caType != null); int pcaCount = 0; Attribute[] pca = PseudoCustomAttribute.GetCustomAttributes(e, caType, out pcaCount); @@ -1394,8 +1388,8 @@ internal static Object[] GetCustomAttributes(RuntimeEventInfo e, RuntimeType caT internal static Object[] GetCustomAttributes(RuntimeFieldInfo field, RuntimeType caType) { - Contract.Requires(field != null); - Contract.Requires(caType != null); + Debug.Assert(field != null); + Debug.Assert(caType != null); int pcaCount = 0; Attribute[] pca = PseudoCustomAttribute.GetCustomAttributes(field, caType, out pcaCount); @@ -1406,8 +1400,8 @@ internal static Object[] GetCustomAttributes(RuntimeFieldInfo field, RuntimeType internal static Object[] GetCustomAttributes(RuntimeParameterInfo parameter, RuntimeType caType) { - Contract.Requires(parameter != null); - Contract.Requires(caType != null); + Debug.Assert(parameter != null); + Debug.Assert(caType != null); int pcaCount = 0; Attribute[] pca = PseudoCustomAttribute.GetCustomAttributes(parameter, caType, out pcaCount); @@ -1418,8 +1412,8 @@ internal static Object[] GetCustomAttributes(RuntimeParameterInfo parameter, Run internal static Object[] GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType) { - Contract.Requires(assembly != null); - Contract.Requires(caType != null); + Debug.Assert(assembly != null); + Debug.Assert(caType != null); int pcaCount = 0; Attribute[] pca = PseudoCustomAttribute.GetCustomAttributes(assembly, caType, out pcaCount); @@ -1431,8 +1425,8 @@ internal static Object[] GetCustomAttributes(RuntimeAssembly assembly, RuntimeTy internal static Object[] GetCustomAttributes(RuntimeModule module, RuntimeType caType) { - Contract.Requires(module != null); - Contract.Requires(caType != null); + Debug.Assert(module != null); + Debug.Assert(caType != null); int pcaCount = 0; Attribute[] pca = PseudoCustomAttribute.GetCustomAttributes(module, caType, out pcaCount); @@ -1457,7 +1451,6 @@ private static bool IsCustomAttributeDefined( { if (decoratedModule.Assembly.ReflectionOnly) throw new InvalidOperationException(SR.Arg_ReflectionOnlyCA); - Contract.EndContractBlock(); CustomAttributeRecord[] car = CustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedMetadataToken); @@ -1513,7 +1506,6 @@ private unsafe static object[] GetCustomAttributes( { if (decoratedModule.Assembly.ReflectionOnly) throw new InvalidOperationException(SR.Arg_ReflectionOnlyCA); - Contract.EndContractBlock(); MetadataImport scope = decoratedModule.MetadataImport; CustomAttributeRecord[] car = CustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedMetadataToken); @@ -1936,8 +1928,8 @@ private static void VerifyPseudoCustomAttribute(RuntimeType pca) #region Internal Static internal static Attribute[] GetCustomAttributes(RuntimeType type, RuntimeType caType, out int count) { - Contract.Requires(type != null); - Contract.Requires(caType != null); + Debug.Assert(type != null); + Debug.Assert(caType != null); count = 0; @@ -1983,8 +1975,8 @@ internal static bool IsDefined(RuntimeType type, RuntimeType caType) internal static Attribute[] GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, out int count) { - Contract.Requires(method != null); - Contract.Requires(caType != null); + Debug.Assert(method != null); + Debug.Assert(caType != null); count = 0; @@ -2031,8 +2023,8 @@ internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType caType) internal static Attribute[] GetCustomAttributes(RuntimeParameterInfo parameter, RuntimeType caType, out int count) { - Contract.Requires(parameter != null); - Contract.Requires(caType != null); + Debug.Assert(parameter != null); + Debug.Assert(caType != null); count = 0; @@ -2114,8 +2106,8 @@ internal static bool IsDefined(RuntimeModule module, RuntimeType caType) internal static Attribute[] GetCustomAttributes(RuntimeFieldInfo field, RuntimeType caType, out int count) { - Contract.Requires(field != null); - Contract.Requires(caType != null); + Debug.Assert(field != null); + Debug.Assert(caType != null); count = 0; @@ -2329,7 +2321,7 @@ internal static StructLayoutAttribute GetStructLayoutCustomAttribute(RuntimeType case TypeAttributes.ExplicitLayout: layoutKind = LayoutKind.Explicit; break; case TypeAttributes.AutoLayout: layoutKind = LayoutKind.Auto; break; case TypeAttributes.SequentialLayout: layoutKind = LayoutKind.Sequential; break; - default: Contract.Assume(false); break; + default: Debug.Fail("Unreachable code"); break; } CharSet charSet = CharSet.None; @@ -2338,7 +2330,7 @@ internal static StructLayoutAttribute GetStructLayoutCustomAttribute(RuntimeType case TypeAttributes.AnsiClass: charSet = CharSet.Ansi; break; case TypeAttributes.AutoClass: charSet = CharSet.Auto; break; case TypeAttributes.UnicodeClass: charSet = CharSet.Unicode; break; - default: Contract.Assume(false); break; + default: Debug.Fail("Unreachable code"); break; } type.GetRuntimeModule().MetadataImport.GetClassLayout(type.MetadataToken, out pack, out size); diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs index 82f460138b93..bcd70c3b873c 100644 --- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs @@ -27,7 +27,6 @@ namespace System.Reflection.Emit using System; using System.Collections.Generic; using System.Diagnostics; - using System.Diagnostics.Contracts; using System.Diagnostics.SymbolStore; using CultureInfo = System.Globalization.CultureInfo; using System.IO; @@ -164,7 +163,7 @@ private Module nGetInMemoryAssemblyModule() internal ModuleBuilder GetModuleBuilder(InternalModuleBuilder module) { - Contract.Requires(module != null); + Debug.Assert(module != null); Debug.Assert(this.InternalAssembly == module.Assembly); lock (SyncRoot) @@ -283,8 +282,6 @@ public static AssemblyBuilder DefineDynamicAssembly( AssemblyName name, AssemblyBuilderAccess access) { - Contract.Ensures(Contract.Result() != null); - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalDefineDynamicAssembly(name, access, ref stackMark, null); @@ -296,8 +293,6 @@ public static AssemblyBuilder DefineDynamicAssembly( AssemblyBuilderAccess access, IEnumerable assemblyAttributes) { - Contract.Ensures(Contract.Result() != null); - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalDefineDynamicAssembly(name, access, @@ -344,8 +339,6 @@ internal static AssemblyBuilder InternalDefineDynamicAssembly( public ModuleBuilder DefineDynamicModule( String name) { - Contract.Ensures(Contract.Result() != null); - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return DefineDynamicModuleInternal(name, false, ref stackMark); } @@ -355,8 +348,6 @@ public ModuleBuilder DefineDynamicModule( String name, bool emitSymbolInfo) // specify if emit symbol info or not { - Contract.Ensures(Contract.Result() != null); - StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return DefineDynamicModuleInternal(name, emitSymbolInfo, ref stackMark); } @@ -383,8 +374,6 @@ private ModuleBuilder DefineDynamicModuleInternalNoLock( throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); if (name[0] == '\0') throw new ArgumentException(SR.Argument_InvalidName, nameof(name)); - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.DefineDynamicModule( " + name + " )"); @@ -682,7 +671,6 @@ private ModuleBuilder GetDynamicModuleNoLock( throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); - Contract.EndContractBlock(); BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.GetDynamicModule( " + name + " )"); int size = m_assemblyData.m_moduleBuilderList.Count; @@ -707,7 +695,6 @@ public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) throw new ArgumentNullException(nameof(con)); if (binaryAttribute == null) throw new ArgumentNullException(nameof(binaryAttribute)); - Contract.EndContractBlock(); lock (SyncRoot) { @@ -742,7 +729,6 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { throw new ArgumentNullException(nameof(customBuilder)); } - Contract.EndContractBlock(); lock (SyncRoot) { diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs index 901588079a78..99c055a99152 100644 --- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs +++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs @@ -18,7 +18,6 @@ namespace System.Reflection.Emit using System.IO; using System.Runtime.Versioning; using System.Diagnostics.SymbolStore; - using System.Diagnostics.Contracts; // This is a package private class. This class hold all of the managed // data member for AssemblyBuilder. Note that what ever data members added to diff --git a/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs index 3ca9b2eb9dc0..47b6f08914c0 100644 --- a/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs @@ -13,7 +13,6 @@ namespace System.Reflection.Emit using System.Diagnostics.SymbolStore; using System.Security; using System.Runtime.InteropServices; - using System.Diagnostics.Contracts; public sealed class ConstructorBuilder : ConstructorInfo { @@ -105,7 +104,6 @@ public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder throw new NotSupportedException(SR.NotSupported_DynamicModule); } - [Pure] public override ParameterInfo[] GetParameters() { ConstructorInfo rci = GetTypeBuilder().GetConstructor(m_methodBuilder.m_parameterTypes); diff --git a/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs index cf5bd11de6ab..cdc9f469b3f2 100644 --- a/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs @@ -21,7 +21,6 @@ using System.Runtime.InteropServices; using System.Globalization; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Reflection.Emit { @@ -121,7 +120,6 @@ internal void InitCustomAttributeBuilder(ConstructorInfo con, Object[] construct throw new ArgumentException(SR.Arg_ArrayLengthsDiffer, "namedProperties, propertyValues"); if (namedFields.Length != fieldValues.Length) throw new ArgumentException(SR.Arg_ArrayLengthsDiffer, "namedFields, fieldValues"); - Contract.EndContractBlock(); if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static || (con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) diff --git a/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs b/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs index b592053f9fc4..5570233ff11a 100644 --- a/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs +++ b/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs @@ -16,7 +16,6 @@ namespace System.Reflection.Emit using System.Threading; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; - using System.Diagnostics.Contracts; using System.Security; internal class DynamicILGenerator : ILGenerator @@ -49,7 +48,6 @@ public override LocalBuilder DeclareLocal(Type localType, bool pinned) LocalBuilder localBuilder; if (localType == null) throw new ArgumentNullException(nameof(localType)); - Contract.EndContractBlock(); RuntimeType rtType = localType as RuntimeType; @@ -72,7 +70,6 @@ public override void Emit(OpCode opcode, MethodInfo meth) { if (meth == null) throw new ArgumentNullException(nameof(meth)); - Contract.EndContractBlock(); int stackchange = 0; int token = 0; @@ -128,7 +125,6 @@ public override void Emit(OpCode opcode, ConstructorInfo con) { if (con == null) throw new ArgumentNullException(nameof(con)); - Contract.EndContractBlock(); RuntimeConstructorInfo rtConstructor = con as RuntimeConstructorInfo; if (rtConstructor == null) @@ -156,7 +152,6 @@ public override void Emit(OpCode opcode, Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); - Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; @@ -173,7 +168,6 @@ public override void Emit(OpCode opcode, FieldInfo field) { if (field == null) throw new ArgumentNullException(nameof(field)); - Contract.EndContractBlock(); RuntimeFieldInfo runtimeField = field as RuntimeFieldInfo; if (runtimeField == null) @@ -194,7 +188,6 @@ public override void Emit(OpCode opcode, String str) { if (str == null) throw new ArgumentNullException(nameof(str)); - Contract.EndContractBlock(); int tempVal = GetTokenForString(str); EnsureCapacity(7); @@ -261,7 +254,6 @@ public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optio if (methodInfo.DeclaringType != null && methodInfo.DeclaringType.ContainsGenericParameters) throw new ArgumentException(SR.Argument_GenericsInvalid, nameof(methodInfo)); - Contract.EndContractBlock(); int tk; int stackchange = 0; @@ -292,7 +284,6 @@ public override void Emit(OpCode opcode, SignatureHelper signature) { if (signature == null) throw new ArgumentNullException(nameof(signature)); - Contract.EndContractBlock(); int stackchange = 0; EnsureCapacity(7); @@ -343,7 +334,6 @@ public override void BeginCatchBlock(Type exceptionType) { if (CurrExcStackCount == 0) throw new NotSupportedException(SR.Argument_NotInExceptionBlock); - Contract.EndContractBlock(); __ExceptionInfo current = CurrExcStack[CurrExcStackCount - 1]; @@ -389,13 +379,11 @@ public override void BeginCatchBlock(Type exceptionType) // debugger related calls. // // - [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override void UsingNamespace(String ns) { throw new NotSupportedException(SR.InvalidOperation_NotAllowedInDynamicMethod); } - [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override void MarkSequencePoint(ISymbolDocumentWriter document, int startLine, int startColumn, diff --git a/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs b/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs index 07d886fccab1..4462135dae1c 100644 --- a/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs +++ b/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs @@ -15,7 +15,6 @@ namespace System.Reflection.Emit using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Diagnostics; - using System.Diagnostics.Contracts; using System.Runtime.InteropServices; public sealed class DynamicMethod : MethodInfo @@ -220,7 +219,6 @@ static private void CheckConsistency(MethodAttributes attributes, CallingConvent throw new NotSupportedException(SR.NotSupported_DynamicMethodFlags); if ((attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public) throw new NotSupportedException(SR.NotSupported_DynamicMethodFlags); - Contract.EndContractBlock(); // only standard or varargs supported if (callingConvention != CallingConventions.Standard && callingConvention != CallingConventions.VarArgs) @@ -431,7 +429,6 @@ internal unsafe RuntimeMethodHandle GetMethodDescriptor() public override MethodInfo GetBaseDefinition() { return this; } - [Pure] public override ParameterInfo[] GetParameters() { return m_dynMethod.GetParameters(); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_dynMethod.GetMethodImplementationFlags(); } @@ -464,7 +461,6 @@ public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder { if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) throw new NotSupportedException(SR.NotSupported_CallToVarArg); - Contract.EndContractBlock(); // // We do not demand any permission here because the caller already has access @@ -648,7 +644,6 @@ public override MethodInfo GetBaseDefinition() return this; } - [Pure] public override ParameterInfo[] GetParameters() { ParameterInfo[] privateParameters = LoadParameters(); @@ -677,7 +672,6 @@ public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute))) return new Object[] { new MethodImplAttribute((MethodImplOptions)GetMethodImplementationFlags()) }; @@ -695,7 +689,6 @@ public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute))) return true; diff --git a/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs index a36882b03632..53566c16b1de 100644 --- a/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs @@ -17,7 +17,6 @@ namespace System.Reflection.Emit { using System; using System.Diagnostics.CodeAnalysis; - using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.InteropServices; using CultureInfo = System.Globalization.CultureInfo; @@ -293,9 +292,6 @@ protected override bool HasElementTypeImpl() return m_typeBuilder.HasElementType; } - // About the SuppressMessageAttribute here - CCRewrite wants us to repeat the base type's precondition - // here, but it will always be true. Rather than adding dead code, I'll silence the warning. - [SuppressMessage("Microsoft.Contracts", "CC1055")] // Legacy: JScript needs it. public override Type GetEnumUnderlyingType() { diff --git a/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs index ef60d05172c1..ff1512829c5c 100644 --- a/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs @@ -16,7 +16,6 @@ using System; using System.Reflection; using System.Runtime.InteropServices; -using System.Diagnostics.Contracts; namespace System.Reflection.Emit { @@ -59,7 +58,6 @@ private void SetMethodSemantics(MethodBuilder mdBuilder, MethodSemanticsAttribut { throw new ArgumentNullException(nameof(mdBuilder)); } - Contract.EndContractBlock(); m_type.ThrowIfCreated(); TypeBuilder.DefineMethodSemantics( @@ -97,7 +95,6 @@ public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) throw new ArgumentNullException(nameof(con)); if (binaryAttribute == null) throw new ArgumentNullException(nameof(binaryAttribute)); - Contract.EndContractBlock(); m_type.ThrowIfCreated(); TypeBuilder.DefineCustomAttribute( @@ -115,7 +112,6 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { throw new ArgumentNullException(nameof(customBuilder)); } - Contract.EndContractBlock(); m_type.ThrowIfCreated(); customBuilder.CreateCustomAttribute(m_module, m_evToken.Token); } diff --git a/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs index d0e9d3483c39..2c4850921cc7 100644 --- a/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs @@ -10,7 +10,6 @@ namespace System.Reflection.Emit using System; using CultureInfo = System.Globalization.CultureInfo; using System.Reflection; - using System.Diagnostics.Contracts; public sealed class FieldBuilder : FieldInfo { @@ -41,7 +40,6 @@ internal FieldBuilder(TypeBuilder typeBuilder, String fieldName, Type type, if (type == typeof(void)) throw new ArgumentException(SR.Argument_BadFieldType); - Contract.EndContractBlock(); m_fieldName = fieldName; m_typeBuilder = typeBuilder; @@ -191,7 +189,6 @@ public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) if (binaryAttribute == null) throw new ArgumentNullException(nameof(binaryAttribute)); - Contract.EndContractBlock(); ModuleBuilder module = m_typeBuilder.Module as ModuleBuilder; @@ -205,7 +202,6 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) throw new ArgumentNullException(nameof(customBuilder)); - Contract.EndContractBlock(); m_typeBuilder.ThrowIfCreated(); diff --git a/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs b/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs index e02278c77710..8905a7f1d9ce 100644 --- a/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs +++ b/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs @@ -16,7 +16,6 @@ namespace System.Reflection.Emit { - public enum FlowControl { Branch = 0, diff --git a/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs index 8256d0e6d565..c682b2861dec 100644 --- a/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs @@ -9,7 +9,6 @@ using System.Collections; using System.Collections.Generic; using System.Globalization; -using System.Diagnostics.Contracts; namespace System.Reflection.Emit { @@ -82,7 +81,6 @@ public override Type MakeArrayType(int rank) { if (rank <= 0) throw new IndexOutOfRangeException(); - Contract.EndContractBlock(); string szrank = ""; if (rank == 1) @@ -200,7 +198,6 @@ public override Type MakeArrayType(int rank) public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); } - [Pure] public override bool IsSubclassOf(Type c) { throw new NotSupportedException(); } #endregion diff --git a/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs b/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs index 09ea180734b9..75a282a24e90 100644 --- a/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs +++ b/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs @@ -31,9 +31,7 @@ internal static T[] EnlargeArray(T[] incoming) internal static T[] EnlargeArray(T[] incoming, int requiredSize) { - Contract.Requires(incoming != null); - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(Contract.Result().Length == requiredSize); + Debug.Assert(incoming != null); T[] temp = new T[requiredSize]; Array.Copy(incoming, 0, temp, 0, incoming.Length); @@ -47,9 +45,7 @@ private static byte[] EnlargeArray(byte[] incoming) private static byte[] EnlargeArray(byte[] incoming, int requiredSize) { - Contract.Requires(incoming != null); - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(Contract.Result().Length == requiredSize); + Debug.Assert(incoming != null); byte[] temp = new byte[requiredSize]; Buffer.BlockCopy(incoming, 0, temp, 0, incoming.Length); @@ -108,8 +104,8 @@ internal ILGenerator(MethodInfo methodBuilder) : this(methodBuilder, 64) internal ILGenerator(MethodInfo methodBuilder, int size) { - Contract.Requires(methodBuilder != null); - Contract.Requires(methodBuilder is MethodBuilder || methodBuilder is DynamicMethod); + Debug.Assert(methodBuilder != null); + Debug.Assert(methodBuilder is MethodBuilder || methodBuilder is DynamicMethod); if (size < defaultSize) { @@ -466,7 +462,6 @@ public virtual void Emit(OpCode opcode, MethodInfo meth) { if (meth == null) throw new ArgumentNullException(nameof(meth)); - Contract.EndContractBlock(); if (opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj)) { @@ -544,7 +539,6 @@ public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] option if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj))) throw new ArgumentException(SR.Argument_NotMethodCallOpcode, nameof(opcode)); - Contract.EndContractBlock(); int stackchange = 0; int tk = GetMethodToken(methodInfo, optionalParameterTypes, false); @@ -577,7 +571,6 @@ public virtual void Emit(OpCode opcode, SignatureHelper signature) { if (signature == null) throw new ArgumentNullException(nameof(signature)); - Contract.EndContractBlock(); int stackchange = 0; ModuleBuilder modBuilder = (ModuleBuilder)m_methodBuilder.Module; @@ -612,7 +605,6 @@ public virtual void Emit(OpCode opcode, ConstructorInfo con) { if (con == null) throw new ArgumentNullException(nameof(con)); - Contract.EndContractBlock(); int stackchange = 0; @@ -749,7 +741,6 @@ public virtual void Emit(OpCode opcode, Label[] labels) { if (labels == null) throw new ArgumentNullException(nameof(labels)); - Contract.EndContractBlock(); // Emitting a switch table @@ -800,7 +791,6 @@ public virtual void Emit(OpCode opcode, LocalBuilder local) { throw new ArgumentNullException(nameof(local)); } - Contract.EndContractBlock(); int tempVal = local.GetLocalIndex(); if (local.GetMethodBuilder() != m_methodBuilder) { @@ -1124,7 +1114,6 @@ public virtual void ThrowException(Type excType) { throw new ArgumentException(SR.Argument_NotExceptionType); } - Contract.EndContractBlock(); ConstructorInfo con = excType.GetConstructor(Type.EmptyTypes); if (con == null) { @@ -1197,7 +1186,6 @@ public virtual void EmitWriteLine(FieldInfo fld) { throw new ArgumentNullException(nameof(fld)); } - Contract.EndContractBlock(); MethodInfo prop = GetConsoleType().GetMethod("get_Out"); Emit(OpCodes.Call, prop); @@ -1279,7 +1267,6 @@ public virtual void UsingNamespace(String usingNamespace) if (usingNamespace.Length == 0) throw new ArgumentException(SR.Argument_EmptyName, nameof(usingNamespace)); - Contract.EndContractBlock(); int index; MethodBuilder methodBuilder = m_methodBuilder as MethodBuilder; @@ -1308,7 +1295,6 @@ public virtual void MarkSequencePoint( { throw new ArgumentOutOfRangeException(nameof(startLine)); } - Contract.EndContractBlock(); m_LineNumberInfo.AddLineNumberInfo(document, m_length, startLine, startColumn, endLine, endColumn); } @@ -1566,7 +1552,7 @@ internal Label GetFinallyEndLabel() // not having a nesting relation. internal bool IsInner(__ExceptionInfo exc) { - Contract.Requires(exc != null); + Debug.Assert(exc != null); Debug.Assert(m_currentCatch > 0, "m_currentCatch > 0"); Debug.Assert(exc.m_currentCatch > 0, "exc.m_currentCatch > 0"); @@ -1681,7 +1667,6 @@ internal void AddScopeInfo(ScopeAction sa, int iOffset) { throw new ArgumentException(SR.Argument_UnmatchingSymScope); } - Contract.EndContractBlock(); // make sure that arrays are large enough to hold addition info EnsureCapacity(); diff --git a/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs index 530a5ee0928a..fda22ab1d67e 100644 --- a/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs @@ -16,7 +16,6 @@ namespace System.Reflection.Emit using System.Collections.Generic; using System.Runtime.InteropServices; using System.Diagnostics; - using System.Diagnostics.Contracts; public sealed class MethodBuilder : MethodInfo { @@ -91,7 +90,6 @@ private void Init(String name, MethodAttributes attributes, CallingConventions c if (mod == null) throw new ArgumentNullException(nameof(mod)); - Contract.EndContractBlock(); if (parameterTypes != null) { @@ -195,7 +193,6 @@ internal void CreateMethodBodyHelper(ILGenerator il) { throw new ArgumentNullException(nameof(il)); } - Contract.EndContractBlock(); __ExceptionInfo[] excp; int counter = 0; @@ -612,7 +609,6 @@ public override Type ReturnType } } - [Pure] public override ParameterInfo[] GetParameters() { if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null) @@ -679,7 +675,6 @@ public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] nam if (names.Length == 0) throw new ArgumentException(SR.Arg_EmptyArray, nameof(names)); - Contract.EndContractBlock(); if (m_inst != null) throw new InvalidOperationException(SR.InvalidOperation_GenericParametersAlreadySet); @@ -825,7 +820,6 @@ public ParameterBuilder DefineParameter(int position, ParameterAttributes attrib { if (position < 0) throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence); - Contract.EndContractBlock(); ThrowIfGeneric(); m_containingType.ThrowIfCreated(); @@ -859,8 +853,6 @@ public void SetImplementationFlags(MethodImplAttributes attributes) public ILGenerator GetILGenerator() { - Contract.Ensures(Contract.Result() != null); - ThrowIfGeneric(); ThrowIfShouldNotHaveBody(); @@ -871,8 +863,6 @@ public ILGenerator GetILGenerator() public ILGenerator GetILGenerator(int size) { - Contract.Ensures(Contract.Result() != null); - ThrowIfGeneric(); ThrowIfShouldNotHaveBody(); @@ -922,7 +912,6 @@ public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) throw new ArgumentNullException(nameof(con)); if (binaryAttribute == null) throw new ArgumentNullException(nameof(binaryAttribute)); - Contract.EndContractBlock(); ThrowIfGeneric(); @@ -939,7 +928,6 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) throw new ArgumentNullException(nameof(customBuilder)); - Contract.EndContractBlock(); ThrowIfGeneric(); diff --git a/src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs index be4bfd5f4850..471f25feb818 100644 --- a/src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs +++ b/src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs @@ -8,7 +8,6 @@ using System.Reflection; using System.Collections; using System.Globalization; -using System.Diagnostics.Contracts; namespace System.Reflection.Emit { @@ -19,7 +18,6 @@ internal static MethodInfo MakeGenericMethod(MethodInfo method, Type[] inst) { if (!method.IsGenericMethodDefinition) throw new InvalidOperationException(); - Contract.EndContractBlock(); return new MethodBuilderInstantiation(method, inst); } @@ -56,7 +54,6 @@ internal override Type[] GetParameterTypes() #endregion #region MethodBase Members - [Pure] public override ParameterInfo[] GetParameters() { throw new NotSupportedException(); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_method.GetMethodImplementationFlags(); } public override RuntimeMethodHandle MethodHandle { get { throw new NotSupportedException(SR.NotSupported_DynamicModule); } } diff --git a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs index 1c65bf91c2d1..c7e6e59f4260 100644 --- a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs @@ -21,7 +21,6 @@ namespace System.Reflection.Emit using System.Runtime.Versioning; using System.Runtime.CompilerServices; using System.Diagnostics; - using System.Diagnostics.Contracts; internal sealed class InternalModuleBuilder : RuntimeModule { @@ -269,7 +268,6 @@ internal MethodToken InternalGetConstructorToken(ConstructorInfo con, bool using if (con == null) throw new ArgumentNullException(nameof(con)); - Contract.EndContractBlock(); int tr; int mr = 0; @@ -824,7 +822,6 @@ public override String Name public override Assembly Assembly { - [Pure] get { return m_assemblyBuilder; @@ -838,8 +835,6 @@ public override Assembly Assembly #region Define Type public TypeBuilder DefineType(String name) { - Contract.Ensures(Contract.Result() != null); - lock (SyncRoot) { return DefineTypeNoLock(name, TypeAttributes.NotPublic, null, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize); @@ -848,8 +843,6 @@ public TypeBuilder DefineType(String name) public TypeBuilder DefineType(String name, TypeAttributes attr) { - Contract.Ensures(Contract.Result() != null); - lock (SyncRoot) { return DefineTypeNoLock(name, attr, null, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize); @@ -858,8 +851,6 @@ public TypeBuilder DefineType(String name, TypeAttributes attr) public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent) { - Contract.Ensures(Contract.Result() != null); - lock (SyncRoot) { // Why do we only call CheckContext here? Why don't we call it in the other overloads? @@ -871,8 +862,6 @@ public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent) public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, int typesize) { - Contract.Ensures(Contract.Result() != null); - lock (SyncRoot) { return DefineTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, typesize); @@ -881,8 +870,6 @@ public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, int public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize) { - Contract.Ensures(Contract.Result() != null); - lock (SyncRoot) { return DefineTypeNoLock(name, attr, parent, null, packingSize, typesize); @@ -891,8 +878,6 @@ public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, Pac public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, Type[] interfaces) { - Contract.Ensures(Contract.Result() != null); - lock (SyncRoot) { return DefineTypeNoLock(name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize); @@ -901,15 +886,11 @@ public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, Typ private TypeBuilder DefineTypeNoLock(String name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize) { - Contract.Ensures(Contract.Result() != null); - return new TypeBuilder(name, attr, parent, interfaces, this, packingSize, typesize, null); ; } public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, PackingSize packsize) { - Contract.Ensures(Contract.Result() != null); - lock (SyncRoot) { return DefineTypeNoLock(name, attr, parent, packsize); @@ -918,8 +899,6 @@ public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, Pac private TypeBuilder DefineTypeNoLock(String name, TypeAttributes attr, Type parent, PackingSize packsize) { - Contract.Ensures(Contract.Result() != null); - return new TypeBuilder(name, attr, parent, null, this, packsize, TypeBuilder.UnspecifiedTypeSize, null); } @@ -931,8 +910,6 @@ private TypeBuilder DefineTypeNoLock(String name, TypeAttributes attr, Type pare // Nested enum types can be defined manually using ModuleBuilder.DefineType. public EnumBuilder DefineEnum(String name, TypeAttributes visibility, Type underlyingType) { - Contract.Ensures(Contract.Result() != null); - CheckContext(underlyingType); lock (SyncRoot) { @@ -957,8 +934,6 @@ public EnumBuilder DefineEnum(String name, TypeAttributes visibility, Type under private EnumBuilder DefineEnumNoLock(String name, TypeAttributes visibility, Type underlyingType) { - Contract.Ensures(Contract.Result() != null); - return new EnumBuilder(name, underlyingType, visibility, this); } @@ -971,16 +946,12 @@ private EnumBuilder DefineEnumNoLock(String name, TypeAttributes visibility, Typ #region Define Global Method public MethodBuilder DefineGlobalMethod(String name, MethodAttributes attributes, Type returnType, Type[] parameterTypes) { - Contract.Ensures(Contract.Result() != null); - return DefineGlobalMethod(name, attributes, CallingConventions.Standard, returnType, parameterTypes); } public MethodBuilder DefineGlobalMethod(String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) { - Contract.Ensures(Contract.Result() != null); - return DefineGlobalMethod(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null); } @@ -1011,8 +982,6 @@ private MethodBuilder DefineGlobalMethodNoLock(String name, MethodAttributes att if ((attributes & MethodAttributes.Static) == 0) throw new ArgumentException(SR.Argument_GlobalFunctionHasToBeStatic); - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); CheckContext(returnType); CheckContext(requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes); @@ -1054,7 +1023,6 @@ public FieldBuilder DefineInitializedData(String name, byte[] data, FieldAttribu // This method will define an initialized Data in .sdata. // We will create a fake TypeDef to represent the data with size. This TypeDef // will be the signature for the Field. - Contract.Ensures(Contract.Result() != null); lock (SyncRoot) { @@ -1071,8 +1039,6 @@ private FieldBuilder DefineInitializedDataNoLock(String name, byte[] data, Field { throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); m_moduleData.m_fHasGlobal = true; return m_moduleData.m_globalTypeBuilder.DefineInitializedData(name, data, attributes); @@ -1080,8 +1046,6 @@ private FieldBuilder DefineInitializedDataNoLock(String name, byte[] data, Field public FieldBuilder DefineUninitializedData(String name, int size, FieldAttributes attributes) { - Contract.Ensures(Contract.Result() != null); - lock (SyncRoot) { return DefineUninitializedDataNoLock(name, size, attributes); @@ -1098,8 +1062,6 @@ private FieldBuilder DefineUninitializedDataNoLock(String name, int size, FieldA { throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); m_moduleData.m_fHasGlobal = true; return m_moduleData.m_globalTypeBuilder.DefineUninitializedData(name, size, attributes); @@ -1134,7 +1096,6 @@ private TypeToken GetTypeTokenWorkerNoLock(Type type, bool getGenericDefinition) { if (type == null) throw new ArgumentNullException(nameof(type)); - Contract.EndContractBlock(); CheckContext(type); @@ -1251,7 +1212,6 @@ private MethodToken GetMethodTokenNoLock(MethodInfo method, bool getGenericTypeD // return the MethodDef token. if (method == null) throw new ArgumentNullException(nameof(method)); - Contract.EndContractBlock(); int tr; int mr = 0; @@ -1443,7 +1403,6 @@ private MethodToken GetArrayMethodTokenNoLock(Type arrayClass, String methodName if (arrayClass.IsArray == false) throw new ArgumentException(SR.Argument_HasToBeArrayClass); - Contract.EndContractBlock(); CheckContext(returnType, arrayClass); CheckContext(parameterTypes); @@ -1500,7 +1459,6 @@ private FieldToken GetFieldTokenNoLock(FieldInfo field) { throw new ArgumentNullException(nameof(field)); } - Contract.EndContractBlock(); int tr; int mr = 0; @@ -1589,7 +1547,6 @@ public StringToken GetStringConstant(String str) { throw new ArgumentNullException(nameof(str)); } - Contract.EndContractBlock(); // Returns a token representing a String constant. If the string // value has already been defined, the existing token will be returned. @@ -1605,7 +1562,6 @@ public SignatureToken GetSignatureToken(SignatureHelper sigHelper) { throw new ArgumentNullException(nameof(sigHelper)); } - Contract.EndContractBlock(); int sigLength; byte[] sigBytes; @@ -1618,7 +1574,6 @@ public SignatureToken GetSignatureToken(byte[] sigBytes, int sigLength) { if (sigBytes == null) throw new ArgumentNullException(nameof(sigBytes)); - Contract.EndContractBlock(); byte[] localSigBytes = new byte[sigBytes.Length]; Buffer.BlockCopy(sigBytes, 0, localSigBytes, 0, sigBytes.Length); @@ -1636,7 +1591,6 @@ public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) throw new ArgumentNullException(nameof(con)); if (binaryAttribute == null) throw new ArgumentNullException(nameof(binaryAttribute)); - Contract.EndContractBlock(); TypeBuilder.DefineCustomAttribute( this, @@ -1652,7 +1606,6 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { throw new ArgumentNullException(nameof(customBuilder)); } - Contract.EndContractBlock(); customBuilder.CreateCustomAttribute(this, 1); // This is hard coding the module token to 1 } @@ -1696,7 +1649,6 @@ public ISymbolDocumentWriter DefineDocument(String url, Guid language, Guid lang // url cannot be null but can be an empty string if (url == null) throw new ArgumentNullException(nameof(url)); - Contract.EndContractBlock(); lock (SyncRoot) { @@ -1715,7 +1667,6 @@ private ISymbolDocumentWriter DefineDocumentNoLock(String url, Guid language, Gu return m_iSymWriter.DefineDocument(url, language, languageVendor, documentType); } - [Pure] public bool IsTransient() { return InternalModule.IsTransientInternal(); diff --git a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs index c597dbe6b4e0..0364ae52abb9 100644 --- a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs +++ b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs @@ -4,7 +4,6 @@ using System; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Globalization; using System.IO; using System.Reflection; diff --git a/src/mscorlib/src/System/Reflection/Emit/OpCodeType.cs b/src/mscorlib/src/System/Reflection/Emit/OpCodeType.cs index 8bf9ffd40d3d..17435c5768e2 100644 --- a/src/mscorlib/src/System/Reflection/Emit/OpCodeType.cs +++ b/src/mscorlib/src/System/Reflection/Emit/OpCodeType.cs @@ -16,7 +16,6 @@ namespace System.Reflection.Emit { - public enum OpCodeType { [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")] diff --git a/src/mscorlib/src/System/Reflection/Emit/OpCodes.cs b/src/mscorlib/src/System/Reflection/Emit/OpCodes.cs index bb2913ebfc54..81257bdd4b77 100644 --- a/src/mscorlib/src/System/Reflection/Emit/OpCodes.cs +++ b/src/mscorlib/src/System/Reflection/Emit/OpCodes.cs @@ -16,7 +16,6 @@ namespace System.Reflection.Emit { - /// /// Internal enum OpCodeValues for opcode values. /// @@ -263,7 +262,6 @@ internal enum OpCodeValues /// public class OpCodes { - private OpCodes() { } diff --git a/src/mscorlib/src/System/Reflection/Emit/Opcode.cs b/src/mscorlib/src/System/Reflection/Emit/Opcode.cs index 37768be9d7ae..72967cdfca18 100644 --- a/src/mscorlib/src/System/Reflection/Emit/Opcode.cs +++ b/src/mscorlib/src/System/Reflection/Emit/Opcode.cs @@ -4,7 +4,6 @@ using System; using System.Threading; -using System.Diagnostics.Contracts; namespace System.Reflection.Emit { @@ -157,7 +156,6 @@ public String Name } } - [Pure] public override bool Equals(Object obj) { if (obj is OpCode) @@ -166,19 +164,16 @@ public override bool Equals(Object obj) return false; } - [Pure] public bool Equals(OpCode obj) { return obj.Value == Value; } - [Pure] public static bool operator ==(OpCode a, OpCode b) { return a.Equals(b); } - [Pure] public static bool operator !=(OpCode a, OpCode b) { return !(a == b); diff --git a/src/mscorlib/src/System/Reflection/Emit/OperandType.cs b/src/mscorlib/src/System/Reflection/Emit/OperandType.cs index 33fe193398d7..6257c5674567 100644 --- a/src/mscorlib/src/System/Reflection/Emit/OperandType.cs +++ b/src/mscorlib/src/System/Reflection/Emit/OperandType.cs @@ -16,7 +16,6 @@ namespace System.Reflection.Emit { - public enum OperandType { InlineBrTarget = 0, diff --git a/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs index 636825956a8c..6f61cac5a712 100644 --- a/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs @@ -16,7 +16,6 @@ using System.Runtime.InteropServices; using System; using System.Reflection; -using System.Diagnostics.Contracts; namespace System.Reflection.Emit { @@ -40,7 +39,6 @@ public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) throw new ArgumentNullException(nameof(con)); if (binaryAttribute == null) throw new ArgumentNullException(nameof(binaryAttribute)); - Contract.EndContractBlock(); TypeBuilder.DefineCustomAttribute( m_methodBuilder.GetModuleBuilder(), @@ -57,7 +55,6 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { throw new ArgumentNullException(nameof(customBuilder)); } - Contract.EndContractBlock(); customBuilder.CreateCustomAttribute((ModuleBuilder)(m_methodBuilder.GetModule()), m_pdToken.Token); } diff --git a/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs index 6dbcba251ff0..9344b53a09b5 100644 --- a/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs @@ -19,7 +19,6 @@ namespace System.Reflection.Emit using System.Reflection; using CultureInfo = System.Globalization.CultureInfo; using System.Runtime.InteropServices; - using System.Diagnostics.Contracts; // // A PropertyBuilder is always associated with a TypeBuilder. The TypeBuilder.DefineProperty @@ -47,7 +46,6 @@ internal PropertyBuilder( throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); if (name[0] == '\0') throw new ArgumentException(SR.Argument_IllegalName, nameof(name)); - Contract.EndContractBlock(); m_name = name; m_moduleBuilder = mod; diff --git a/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs b/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs index fd1a8e70fe84..94d2b12dce98 100644 --- a/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs +++ b/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs @@ -7,7 +7,6 @@ using System.Text; using System; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -289,8 +288,8 @@ private void AddOneArgTypeHelper(Type clsArgument, Type[] requiredCustomModifier // This function will not increase the argument count. It only fills in bytes // in the signature based on clsArgument. This helper is called for return type. - Contract.Requires(clsArgument != null); - Contract.Requires((optionalCustomModifiers == null && requiredCustomModifiers == null) || !clsArgument.ContainsGenericParameters); + Debug.Assert(clsArgument != null); + Debug.Assert((optionalCustomModifiers == null && requiredCustomModifiers == null) || !clsArgument.ContainsGenericParameters); if (optionalCustomModifiers != null) { diff --git a/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs b/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs index 9e45cd3fe069..3e64b48798df 100644 --- a/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs +++ b/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs @@ -16,7 +16,6 @@ namespace System.Reflection.Emit { - public enum StackBehaviour { Pop0 = 0, diff --git a/src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs b/src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs index 42713b86dbff..5e5668ac7b59 100644 --- a/src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs +++ b/src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs @@ -9,7 +9,6 @@ namespace System.Reflection.Emit using System.Runtime.InteropServices; using System; using System.Reflection; - using System.Diagnostics.Contracts; using CultureInfo = System.Globalization.CultureInfo; internal sealed class SymbolMethod : MethodInfo @@ -96,7 +95,6 @@ public override Type DeclaringType #endregion #region MethodBase Overrides - [Pure] public override ParameterInfo[] GetParameters() { throw new NotSupportedException(SR.NotSupported_SymbolMethod); diff --git a/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs b/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs index ca2f7d9d6e8e..6057c1da7214 100644 --- a/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs +++ b/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs @@ -9,7 +9,6 @@ namespace System.Reflection.Emit using System.Runtime.InteropServices; using System; using System.Reflection; - using System.Diagnostics.Contracts; using CultureInfo = System.Globalization.CultureInfo; internal enum TypeKind @@ -234,7 +233,6 @@ internal void SetElementType(Type baseType) { if (baseType == null) throw new ArgumentNullException(nameof(baseType)); - Contract.EndContractBlock(); m_baseType = baseType; } @@ -294,7 +292,6 @@ public override Type MakeArrayType(int rank) { if (rank <= 0) throw new IndexOutOfRangeException(); - Contract.EndContractBlock(); string szrank = ""; if (rank == 1) @@ -316,7 +313,6 @@ public override int GetArrayRank() { if (!IsArray) throw new NotSupportedException(SR.NotSupported_SubclassOverride); - Contract.EndContractBlock(); return m_cRank; } diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs index 2f550a4e401f..c07f9e736e24 100644 --- a/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs +++ b/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs @@ -17,7 +17,6 @@ namespace System.Reflection.Emit using System.Threading; using System.Runtime.Versioning; using System.Diagnostics; - using System.Diagnostics.Contracts; public enum PackingSize @@ -55,7 +54,6 @@ public CustAttr(ConstructorInfo con, byte[] binaryAttribute) if (binaryAttribute == null) throw new ArgumentNullException(nameof(binaryAttribute)); - Contract.EndContractBlock(); m_con = con; m_binaryAttribute = binaryAttribute; @@ -65,7 +63,6 @@ public CustAttr(CustomAttributeBuilder customBuilder) { if (customBuilder == null) throw new ArgumentNullException(nameof(customBuilder)); - Contract.EndContractBlock(); m_customBuilder = customBuilder; } @@ -106,7 +103,6 @@ public static MethodInfo GetMethod(Type type, MethodInfo method) if (type.GetGenericTypeDefinition() != method.DeclaringType) throw new ArgumentException(SR.Argument_InvalidMethodDeclaringType, nameof(type)); - Contract.EndContractBlock(); // The following converts from Type or TypeBuilder of G to TypeBuilderInstantiation G. These types // both logically represent the same thing. The runtime displays a similar convention by having @@ -126,7 +122,6 @@ public static ConstructorInfo GetConstructor(Type type, ConstructorInfo construc if (!constructor.DeclaringType.IsGenericTypeDefinition) throw new ArgumentException(SR.Argument_ConstructorNeedGenericDeclaringType, nameof(constructor)); - Contract.EndContractBlock(); if (!(type is TypeBuilderInstantiation)) throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type)); @@ -147,7 +142,6 @@ public static FieldInfo GetField(Type type, FieldInfo field) if (!field.DeclaringType.IsGenericTypeDefinition) throw new ArgumentException(SR.Argument_FieldNeedGenericDeclaringType, nameof(field)); - Contract.EndContractBlock(); if (!(type is TypeBuilderInstantiation)) throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type)); @@ -267,7 +261,6 @@ internal static extern int SetParamInfo(RuntimeModule module, int tkMethod, int #endregion #region Internal\Private Static Members - [Pure] internal static bool IsTypeEqual(Type t1, Type t2) { // Maybe we are lucky that they are equal in the first place @@ -482,7 +475,7 @@ internal TypeBuilder(ModuleBuilder module) // ctor for generic method parameter internal TypeBuilder(string szName, int genParamPos, MethodBuilder declMeth) { - Contract.Requires(declMeth != null); + Debug.Assert(declMeth != null); m_declMeth = declMeth; m_DeclaringType = m_declMeth.GetTypeBuilder(); m_module = declMeth.GetModuleBuilder(); @@ -492,7 +485,7 @@ internal TypeBuilder(string szName, int genParamPos, MethodBuilder declMeth) // ctor for generic type parameter private TypeBuilder(string szName, int genParamPos, TypeBuilder declType) { - Contract.Requires(declType != null); + Debug.Assert(declType != null); m_DeclaringType = declType; m_module = declType.GetModuleBuilder(); InitAsGenericParam(szName, genParamPos); @@ -534,7 +527,6 @@ private void Init(String fullname, TypeAttributes attr, Type parent, Type[] inte if (fullname.Length > 1023) throw new ArgumentException(SR.Argument_TypeNameTooLong, nameof(fullname)); - Contract.EndContractBlock(); int i; m_module = module; @@ -634,7 +626,6 @@ private FieldBuilder DefineDataHelper(String name, byte[] data, int size, FieldA if (size <= 0 || size >= 0x003f0000) throw new ArgumentException(SR.Argument_BadSizeForData); - Contract.EndContractBlock(); ThrowIfCreated(); @@ -694,7 +685,6 @@ private void VerifyTypeAttributes(TypeAttributes attr) } } - [Pure] public bool IsCreated() { return m_hasBeenCreated; @@ -825,7 +815,6 @@ public override Guid GUID { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); return m_bakedRuntimeType.GUID; } @@ -836,7 +825,6 @@ public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); return m_bakedRuntimeType.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters); } @@ -885,7 +873,6 @@ protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); return m_bakedRuntimeType.GetConstructor(bindingAttr, binder, callConvention, types, modifiers); } @@ -894,7 +881,6 @@ public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); return m_bakedRuntimeType.GetConstructors(bindingAttr); } @@ -904,7 +890,6 @@ protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAtt { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); if (types == null) { @@ -920,7 +905,6 @@ public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); return m_bakedRuntimeType.GetMethods(bindingAttr); } @@ -929,7 +913,6 @@ public override FieldInfo GetField(String name, BindingFlags bindingAttr) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); return m_bakedRuntimeType.GetField(name, bindingAttr); } @@ -938,7 +921,6 @@ public override FieldInfo[] GetFields(BindingFlags bindingAttr) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); return m_bakedRuntimeType.GetFields(bindingAttr); } @@ -947,7 +929,6 @@ public override Type GetInterface(String name, bool ignoreCase) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); return m_bakedRuntimeType.GetInterface(name, ignoreCase); } @@ -971,7 +952,6 @@ public override EventInfo GetEvent(String name, BindingFlags bindingAttr) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); return m_bakedRuntimeType.GetEvent(name, bindingAttr); } @@ -980,7 +960,6 @@ public override EventInfo[] GetEvents() { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); return m_bakedRuntimeType.GetEvents(); } @@ -995,7 +974,6 @@ public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); return m_bakedRuntimeType.GetProperties(bindingAttr); } @@ -1004,7 +982,6 @@ public override Type[] GetNestedTypes(BindingFlags bindingAttr) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); return m_bakedRuntimeType.GetNestedTypes(bindingAttr); } @@ -1013,7 +990,6 @@ public override Type GetNestedType(String name, BindingFlags bindingAttr) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); return m_bakedRuntimeType.GetNestedType(name, bindingAttr); } @@ -1022,7 +998,6 @@ public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFla { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); return m_bakedRuntimeType.GetMember(name, type, bindingAttr); } @@ -1031,7 +1006,6 @@ public override InterfaceMapping GetInterfaceMap(Type interfaceType) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); return m_bakedRuntimeType.GetInterfaceMap(interfaceType); } @@ -1040,7 +1014,6 @@ public override EventInfo[] GetEvents(BindingFlags bindingAttr) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); return m_bakedRuntimeType.GetEvents(bindingAttr); } @@ -1049,7 +1022,6 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); return m_bakedRuntimeType.GetMembers(bindingAttr); } @@ -1160,7 +1132,6 @@ public override bool IsSecurityTransparent get { return false; } } - [Pure] public override bool IsSubclassOf(Type c) { Type p = this; @@ -1221,7 +1192,6 @@ public override Type MakeArrayType(int rank) { if (rank <= 0) throw new IndexOutOfRangeException(); - Contract.EndContractBlock(); string szrank = ""; if (rank == 1) @@ -1245,7 +1215,6 @@ public override Object[] GetCustomAttributes(bool inherit) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - Contract.EndContractBlock(); return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, typeof(object) as RuntimeType, inherit); } @@ -1257,7 +1226,6 @@ public override Object[] GetCustomAttributes(Type attributeType, bool inherit) if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; @@ -1274,7 +1242,6 @@ public override bool IsDefined(Type attributeType, bool inherit) if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; @@ -1310,7 +1277,6 @@ public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] nam if (names.Length == 0) throw new ArgumentException(); - Contract.EndContractBlock(); for (int i = 0; i < names.Length; i++) if (names[i] == null) @@ -1363,7 +1329,6 @@ private void DefineMethodOverrideNoLock(MethodInfo methodInfoBody, MethodInfo me if (methodInfoDeclaration == null) throw new ArgumentNullException(nameof(methodInfoDeclaration)); - Contract.EndContractBlock(); ThrowIfCreated(); @@ -1382,30 +1347,22 @@ private void DefineMethodOverrideNoLock(MethodInfo methodInfoBody, MethodInfo me public MethodBuilder DefineMethod(String name, MethodAttributes attributes, Type returnType, Type[] parameterTypes) { - Contract.Ensures(Contract.Result() != null); - return DefineMethod(name, attributes, CallingConventions.Standard, returnType, parameterTypes); } public MethodBuilder DefineMethod(String name, MethodAttributes attributes) { - Contract.Ensures(Contract.Result() != null); - return DefineMethod(name, attributes, CallingConventions.Standard, null, null); } public MethodBuilder DefineMethod(String name, MethodAttributes attributes, CallingConventions callingConvention) { - Contract.Ensures(Contract.Result() != null); - return DefineMethod(name, attributes, callingConvention, null, null); } public MethodBuilder DefineMethod(String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) { - Contract.Ensures(Contract.Result() != null); - return DefineMethod(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null); } @@ -1413,8 +1370,6 @@ public MethodBuilder DefineMethod(String name, MethodAttributes attributes, Call Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) { - Contract.Ensures(Contract.Result() != null); - lock (SyncRoot) { return DefineMethodNoLock(name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, @@ -1432,8 +1387,6 @@ private MethodBuilder DefineMethodNoLock(String name, MethodAttributes attribute if (name.Length == 0) throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); CheckContext(returnType); CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes); @@ -1736,7 +1689,6 @@ private FieldBuilder DefineInitializedDataNoLock(String name, byte[] data, Field { if (data == null) throw new ArgumentNullException(nameof(data)); - Contract.EndContractBlock(); // This method will define an initialized Data in .sdata. // We will create a fake TypeDef to represent the data with size. This TypeDef @@ -1804,7 +1756,6 @@ private PropertyBuilder DefinePropertyNoLock(String name, PropertyAttributes att throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); - Contract.EndContractBlock(); CheckContext(returnType); CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes); @@ -1861,7 +1812,6 @@ private EventBuilder DefineEventNoLock(String name, EventAttributes attributes, throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); if (name[0] == '\0') throw new ArgumentException(SR.Argument_IllegalName, nameof(name)); - Contract.EndContractBlock(); int tkType; EventToken evToken; @@ -2149,7 +2099,6 @@ public void AddInterfaceImplementation(Type interfaceType) { throw new ArgumentNullException(nameof(interfaceType)); } - Contract.EndContractBlock(); CheckContext(interfaceType); @@ -2180,7 +2129,6 @@ public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) if (binaryAttribute == null) throw new ArgumentNullException(nameof(binaryAttribute)); - Contract.EndContractBlock(); TypeBuilder.DefineCustomAttribute(m_module, m_tdType.Token, ((ModuleBuilder)m_module).GetConstructorToken(con).Token, binaryAttribute, false, false); @@ -2190,7 +2138,6 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) throw new ArgumentNullException(nameof(customBuilder)); - Contract.EndContractBlock(); customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, m_tdType.Token); } diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs index ab5b7eeaa545..ed2e1be86603 100644 --- a/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs +++ b/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs @@ -8,7 +8,7 @@ using System.Reflection; using System.Collections; using System.Globalization; -using System.Diagnostics.Contracts; +using System.Diagnostics; namespace System.Reflection.Emit { @@ -23,14 +23,13 @@ public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo) #region Static Members internal static Type MakeGenericType(Type type, Type[] typeArguments) { - Contract.Requires(type != null, "this is only called from RuntimeType.MakeGenericType and TypeBuilder.MakeGenericType so 'type' cannot be null"); + Debug.Assert(type != null, "this is only called from RuntimeType.MakeGenericType and TypeBuilder.MakeGenericType so 'type' cannot be null"); if (!type.IsGenericTypeDefinition) throw new InvalidOperationException(); if (typeArguments == null) throw new ArgumentNullException(nameof(typeArguments)); - Contract.EndContractBlock(); foreach (Type t in typeArguments) { @@ -94,7 +93,6 @@ public override Type MakeArrayType(int rank) { if (rank <= 0) throw new IndexOutOfRangeException(); - Contract.EndContractBlock(); string comma = ""; for (int i = 1; i < rank; i++) @@ -225,7 +223,6 @@ public override bool ContainsGenericParameters public override Type MakeGenericType(params Type[] inst) { throw new InvalidOperationException(SR.Arg_NotGenericTypeDefinition); } public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); } - [Pure] public override bool IsSubclassOf(Type c) { throw new NotSupportedException(); diff --git a/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs index 3894d9115be0..9c406f81cb36 100644 --- a/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs +++ b/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs @@ -10,7 +10,6 @@ using System.Collections.Generic; using System.Globalization; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Reflection.Emit { @@ -55,7 +54,6 @@ internal override Type[] GetParameterTypes() #endregion #region MethodBase Members - [Pure] public override ParameterInfo[] GetParameters() { return m_method.GetParameters(); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_method.GetMethodImplementationFlags(); } public override RuntimeMethodHandle MethodHandle { get { return m_method.MethodHandle; } } @@ -73,7 +71,6 @@ public override MethodInfo MakeGenericMethod(params Type[] typeArgs) { if (!IsGenericMethodDefinition) throw new InvalidOperationException(SR.Arg_NotGenericMethodDefinition); - Contract.EndContractBlock(); return MethodBuilderInstantiation.MakeGenericMethod(this, typeArgs); } @@ -151,7 +148,6 @@ internal int MetadataTokenInternal #endregion #region MethodBase Members - [Pure] public override ParameterInfo[] GetParameters() { return m_ctor.GetParameters(); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_ctor.GetMethodImplementationFlags(); } public override RuntimeMethodHandle MethodHandle { get { return m_ctor.MethodHandle; } } diff --git a/src/mscorlib/src/System/Reflection/ExceptionHandlingClause.cs b/src/mscorlib/src/System/Reflection/ExceptionHandlingClause.cs index a61ed5e385c3..66ad4eb7a951 100644 --- a/src/mscorlib/src/System/Reflection/ExceptionHandlingClause.cs +++ b/src/mscorlib/src/System/Reflection/ExceptionHandlingClause.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Globalization; -using System.Diagnostics.Contracts; namespace System.Reflection { @@ -16,7 +15,6 @@ protected ExceptionHandlingClause() { } #region Private Data Members private MethodBody m_methodBody; - [ContractPublicPropertyName("Flags")] private ExceptionHandlingClauseOptions m_flags; private int m_tryOffset; private int m_tryLength; diff --git a/src/mscorlib/src/System/Reflection/MdImport.cs b/src/mscorlib/src/System/Reflection/MdImport.cs index 9230ffa9ef2b..d2de707528a4 100644 --- a/src/mscorlib/src/System/Reflection/MdImport.cs +++ b/src/mscorlib/src/System/Reflection/MdImport.cs @@ -16,7 +16,6 @@ using System.Runtime.InteropServices; using System.Configuration.Assemblies; using System.Runtime.Versioning; -using System.Diagnostics.Contracts; namespace System.Reflection { @@ -171,7 +170,6 @@ public byte this[int index] { if (index < 0 || index >= m_length) throw new IndexOutOfRangeException(); - Contract.EndContractBlock(); unsafe { @@ -262,7 +260,7 @@ public int this[int index] { get { - Contract.Requires(0 <= index && index < Length); + Debug.Assert(0 <= index && index < Length); if (largeResult != null) return largeResult[index]; diff --git a/src/mscorlib/src/System/Reflection/RtFieldInfo.cs b/src/mscorlib/src/System/Reflection/RtFieldInfo.cs index 856d254d4795..e4b592d11743 100644 --- a/src/mscorlib/src/System/Reflection/RtFieldInfo.cs +++ b/src/mscorlib/src/System/Reflection/RtFieldInfo.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Threading; @@ -286,7 +285,6 @@ public override Object GetValueDirect(TypedReference obj) { if (obj.IsNull) throw new ArgumentException(SR.Arg_TypedReference_Null); - Contract.EndContractBlock(); unsafe { @@ -309,7 +307,6 @@ public override void SetValueDirect(TypedReference obj, Object value) { if (obj.IsNull) throw new ArgumentException(SR.Arg_TypedReference_Null); - Contract.EndContractBlock(); unsafe { diff --git a/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs b/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs index cd9c715eeca9..138955baec47 100644 --- a/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs +++ b/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs @@ -14,7 +14,6 @@ using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Threading; -using System.Diagnostics.Contracts; namespace System.Reflection { @@ -247,7 +246,6 @@ public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; @@ -261,7 +259,6 @@ public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; @@ -309,7 +306,6 @@ internal static AssemblyName CreateAssemblyName( { if (assemblyString == null) throw new ArgumentNullException(nameof(assemblyString)); - Contract.EndContractBlock(); if ((assemblyString.Length == 0) || (assemblyString[0] == '\0')) @@ -344,7 +340,6 @@ internal static RuntimeAssembly InternalLoadAssemblyName( { if (assemblyRef == null) throw new ArgumentNullException(nameof(assemblyRef)); - Contract.EndContractBlock(); if (assemblyRef.CodeBase != null) { @@ -732,7 +727,6 @@ internal Assembly InternalGetSatelliteAssembly(CultureInfo culture, { if (culture == null) throw new ArgumentNullException(nameof(culture)); - Contract.EndContractBlock(); String name = GetSimpleName() + ".resources"; diff --git a/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs index 9b11a858df78..e7a548e87051 100644 --- a/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs +++ b/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Globalization; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; @@ -75,8 +74,6 @@ internal RuntimeConstructorInfo( RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags) { - Contract.Ensures(methodAttributes == RuntimeMethodHandle.GetAttributes(handle)); - m_bindingFlags = bindingFlags; m_reflectedTypeCache = reflectedTypeCache; m_declaringType = declaringType; @@ -161,7 +158,6 @@ public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; @@ -175,7 +171,6 @@ public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; @@ -244,7 +239,6 @@ internal override ParameterInfo[] GetParametersNoCopy() return m_parameters; } - [Pure] public override ParameterInfo[] GetParameters() { ParameterInfo[] parameters = GetParametersNoCopy(); @@ -293,7 +287,6 @@ internal static void CheckCanCreateInstance(Type declaringType, bool isVarArg) { if (declaringType == null) throw new ArgumentNullException(nameof(declaringType)); - Contract.EndContractBlock(); // ctor is ReflectOnly if (declaringType is ReflectionOnlyType) diff --git a/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs index beea874c9d01..bd8c451fe7bb 100644 --- a/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs +++ b/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; namespace System.Reflection @@ -32,8 +31,8 @@ internal RuntimeEventInfo() } internal RuntimeEventInfo(int tkEvent, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate) { - Contract.Requires(declaredType != null); - Contract.Requires(reflectedTypeCache != null); + Debug.Assert(declaredType != null); + Debug.Assert(reflectedTypeCache != null); Debug.Assert(!reflectedTypeCache.IsGlobal); MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport; @@ -90,7 +89,6 @@ public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; @@ -104,7 +102,6 @@ public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; diff --git a/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs index 9f1f63409350..56f89e618fe7 100644 --- a/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs +++ b/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Collections.Generic; -using System.Diagnostics.Contracts; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; namespace System.Reflection @@ -88,7 +87,6 @@ public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; @@ -102,7 +100,6 @@ public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; diff --git a/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs index 6addf7471830..1419175b6541 100644 --- a/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs +++ b/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Globalization; using System.Security; using System.Text; @@ -69,8 +68,6 @@ internal RuntimeMethodInfo( RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive) { - Contract.Ensures(!m_handle.IsNull()); - Debug.Assert(!handle.IsNullHandle()); Debug.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle)); @@ -258,7 +255,6 @@ public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; @@ -272,7 +268,6 @@ public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; @@ -356,7 +351,6 @@ internal override ParameterInfo[] GetParametersNoCopy() return m_parameters; } - [System.Diagnostics.Contracts.Pure] public override ParameterInfo[] GetParameters() { FetchNonReturnParameters(); @@ -544,8 +538,6 @@ public override ParameterInfo ReturnParameter { get { - Contract.Ensures(m_returnParameter != null); - FetchReturnParameter(); return m_returnParameter as ParameterInfo; } @@ -617,7 +609,6 @@ private Delegate CreateDelegateInternal(Type delegateType, Object firstArgument, // Validate the parameters. if (delegateType == null) throw new ArgumentNullException(nameof(delegateType)); - Contract.EndContractBlock(); RuntimeType rtType = delegateType as RuntimeType; if (rtType == null) @@ -642,7 +633,6 @@ public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation) { if (methodInstantiation == null) throw new ArgumentNullException(nameof(methodInstantiation)); - Contract.EndContractBlock(); RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length]; @@ -711,7 +701,6 @@ public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); - Contract.EndContractBlock(); return RuntimeType.GetMethodBase(m_declaringType, RuntimeMethodHandle.StripMethodInstantiation(this)) as MethodInfo; } diff --git a/src/mscorlib/src/System/Reflection/RuntimeModule.cs b/src/mscorlib/src/System/Reflection/RuntimeModule.cs index f9b733736d17..2ddbb278844e 100644 --- a/src/mscorlib/src/System/Reflection/RuntimeModule.cs +++ b/src/mscorlib/src/System/Reflection/RuntimeModule.cs @@ -8,7 +8,6 @@ using System.Runtime.CompilerServices; using System.Security; using System.Globalization; -using System.Diagnostics.Contracts; namespace System.Reflection { @@ -414,7 +413,6 @@ public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; @@ -428,7 +426,6 @@ public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; @@ -570,7 +567,6 @@ public override String Name public override Assembly Assembly { - [Pure] get { return GetRuntimeAssembly(); diff --git a/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs index 8f070b68278e..5048af3950cd 100644 --- a/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs +++ b/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using MdToken = System.Reflection.MetadataToken; @@ -186,7 +185,7 @@ private RuntimeParameterInfo( Signature signature, MetadataImport scope, int tkParamDef, int position, ParameterAttributes attributes, MemberInfo member) { - Contract.Requires(member != null); + Debug.Assert(member != null); Debug.Assert(MdToken.IsNullToken(tkParamDef) == scope.Equals(MetadataImport.EmptyImport)); Debug.Assert(MdToken.IsNullToken(tkParamDef) || MdToken.IsTokenOfType(tkParamDef, MetadataTokenType.ParamDef)); @@ -397,7 +396,7 @@ private Object GetDefaultValueInternal(bool raw) private static Decimal GetRawDecimalConstant(CustomAttributeData attr) { - Contract.Requires(attr.Constructor.DeclaringType == typeof(DecimalConstantAttribute)); + Debug.Assert(attr.Constructor.DeclaringType == typeof(DecimalConstantAttribute)); foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments) { @@ -441,8 +440,8 @@ private static Decimal GetRawDecimalConstant(CustomAttributeData attr) private static DateTime GetRawDateTimeConstant(CustomAttributeData attr) { - Contract.Requires(attr.Constructor.DeclaringType == typeof(DateTimeConstantAttribute)); - Contract.Requires(attr.ConstructorArguments.Count == 1); + Debug.Assert(attr.Constructor.DeclaringType == typeof(DateTimeConstantAttribute)); + Debug.Assert(attr.ConstructorArguments.Count == 1); foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments) { @@ -518,7 +517,6 @@ public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); if (MdToken.IsNullToken(m_tkParamDef)) return Array.Empty(); @@ -535,7 +533,6 @@ public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); if (MdToken.IsNullToken(m_tkParamDef)) return false; diff --git a/src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs b/src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs index 2d54d752241c..2315e425748c 100644 --- a/src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs +++ b/src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Globalization; using System.Text; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; @@ -32,8 +31,8 @@ internal unsafe sealed class RuntimePropertyInfo : PropertyInfo internal RuntimePropertyInfo( int tkProperty, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate) { - Contract.Requires(declaredType != null); - Contract.Requires(reflectedTypeCache != null); + Debug.Assert(declaredType != null); + Debug.Assert(reflectedTypeCache != null); Debug.Assert(!reflectedTypeCache.IsGlobal); MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport; @@ -111,9 +110,9 @@ internal bool EqualsSig(RuntimePropertyInfo target) // End Class // - Contract.Requires(Name.Equals(target.Name)); - Contract.Requires(this != target); - Contract.Requires(this.ReflectedType == target.ReflectedType); + Debug.Assert(Name.Equals(target.Name)); + Debug.Assert(this != target); + Debug.Assert(this.ReflectedType == target.ReflectedType); return Signature.CompareSig(this.Signature, target.Signature); } @@ -155,7 +154,6 @@ public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; @@ -169,7 +167,6 @@ public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; diff --git a/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs b/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs index 7d445deba27d..58c99242a8d7 100644 --- a/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs +++ b/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs @@ -26,7 +26,6 @@ namespace System.Resources using System.Text; using System.Threading; using System.Diagnostics; - using System.Diagnostics.Contracts; internal class FileBasedResourceGroveler : IResourceGroveler { diff --git a/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs b/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs index a4e698276f51..4548b93dd4e4 100644 --- a/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs +++ b/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs @@ -28,7 +28,6 @@ namespace System.Resources using System.Text; using System.Threading; using System.Diagnostics; - using System.Diagnostics.Contracts; using Microsoft.Win32; // @@ -48,7 +47,7 @@ public ManifestBasedResourceGroveler(ResourceManager.ResourceManagerMediator med { // here and below: convert asserts to preconditions where appropriate when we get // contracts story in place. - Contract.Requires(mediator != null, "mediator shouldn't be null; check caller"); + Debug.Assert(mediator != null, "mediator shouldn't be null; check caller"); _mediator = mediator; } @@ -317,8 +316,8 @@ internal ResourceSet CreateResourceSet(Stream store, Assembly assembly) private Stream GetManifestResourceStream(RuntimeAssembly satellite, String fileName, ref StackCrawlMark stackMark) { - Contract.Requires(satellite != null, "satellite shouldn't be null; check caller"); - Contract.Requires(fileName != null, "fileName shouldn't be null; check caller"); + Debug.Assert(satellite != null, "satellite shouldn't be null; check caller"); + Debug.Assert(fileName != null, "fileName shouldn't be null; check caller"); // If we're looking in the main assembly AND if the main assembly was the person who // created the ResourceManager, skip a security check for private manifest resources. @@ -341,8 +340,8 @@ private Stream GetManifestResourceStream(RuntimeAssembly satellite, String fileN [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod private Stream CaseInsensitiveManifestResourceStreamLookup(RuntimeAssembly satellite, String name) { - Contract.Requires(satellite != null, "satellite shouldn't be null; check caller"); - Contract.Requires(name != null, "name shouldn't be null; check caller"); + Debug.Assert(satellite != null, "satellite shouldn't be null; check caller"); + Debug.Assert(name != null, "name shouldn't be null; check caller"); StringBuilder sb = new StringBuilder(); if (_mediator.LocationInfo != null) diff --git a/src/mscorlib/src/System/Resources/ResourceManager.cs b/src/mscorlib/src/System/Resources/ResourceManager.cs index 7c565adbbb76..0e9780169a61 100644 --- a/src/mscorlib/src/System/Resources/ResourceManager.cs +++ b/src/mscorlib/src/System/Resources/ResourceManager.cs @@ -31,7 +31,6 @@ namespace System.Resources using System.Collections.Generic; using System.Runtime.Versioning; using System.Diagnostics; - using System.Diagnostics.Contracts; #if FEATURE_APPX // @@ -281,7 +280,6 @@ private ResourceManager(String baseName, String resourceDir, Type usingResourceS throw new ArgumentNullException(nameof(baseName)); if (null == resourceDir) throw new ArgumentNullException(nameof(resourceDir)); - Contract.EndContractBlock(); BaseNameField = baseName; @@ -306,7 +304,6 @@ public ResourceManager(String baseName, Assembly assembly) if (null == assembly) throw new ArgumentNullException(nameof(assembly)); - Contract.EndContractBlock(); if (!(assembly is RuntimeAssembly)) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); @@ -336,7 +333,6 @@ public ResourceManager(String baseName, Assembly assembly, Type usingResourceSet throw new ArgumentNullException(nameof(baseName)); if (null == assembly) throw new ArgumentNullException(nameof(assembly)); - Contract.EndContractBlock(); if (!(assembly is RuntimeAssembly)) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); @@ -363,7 +359,6 @@ public ResourceManager(Type resourceSource) { if (null == resourceSource) throw new ArgumentNullException(nameof(resourceSource)); - Contract.EndContractBlock(); if (!(resourceSource is RuntimeType)) throw new ArgumentException(SR.Argument_MustBeRuntimeType); @@ -597,7 +592,6 @@ public virtual ResourceSet GetResourceSet(CultureInfo culture, bool createIfNotE { if (null == culture) throw new ArgumentNullException(nameof(culture)); - Contract.EndContractBlock(); Dictionary localResourceSets = _resourceSets; ResourceSet rs; @@ -756,7 +750,6 @@ protected static Version GetSatelliteContractVersion(Assembly a) { throw new ArgumentNullException(nameof(a), SR.ArgumentNull_Assembly); } - Contract.EndContractBlock(); // Return null. The calling code will use the assembly version instead to avoid potential type // and library loads caused by CA lookup. NetCF uses the assembly version always. @@ -1086,7 +1079,6 @@ public virtual String GetString(String name, CultureInfo culture) { if (null == name) throw new ArgumentNullException(nameof(name)); - Contract.EndContractBlock(); #if FEATURE_APPX if (s_IsAppXModel) @@ -1196,7 +1188,6 @@ private Object GetObject(String name, CultureInfo culture, bool wrapUnmanagedMem { if (null == name) throw new ArgumentNullException(nameof(name)); - Contract.EndContractBlock(); #if FEATURE_APPX if (s_IsAppXModel) diff --git a/src/mscorlib/src/System/Resources/ResourceReader.cs b/src/mscorlib/src/System/Resources/ResourceReader.cs index b4bb28cb6b97..0658032f7d53 100644 --- a/src/mscorlib/src/System/Resources/ResourceReader.cs +++ b/src/mscorlib/src/System/Resources/ResourceReader.cs @@ -134,7 +134,6 @@ public ResourceReader(Stream stream) throw new ArgumentNullException(nameof(stream)); if (!stream.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable); - Contract.EndContractBlock(); _resCache = new Dictionary(FastResourceComparer.Default); _store = new BinaryReader(stream, Encoding.UTF8); @@ -151,9 +150,9 @@ public ResourceReader(Stream stream) // and values, coupled to this ResourceReader). internal ResourceReader(Stream stream, Dictionary resCache) { - Contract.Requires(stream != null, "Need a stream!"); - Contract.Requires(stream.CanRead, "Stream should be readable!"); - Contract.Requires(resCache != null, "Need a Dictionary!"); + Debug.Assert(stream != null, "Need a stream!"); + Debug.Assert(stream.CanRead, "Stream should be readable!"); + Debug.Assert(resCache != null, "Need a Dictionary!"); _resCache = resCache; _store = new BinaryReader(stream, Encoding.UTF8); @@ -420,20 +419,9 @@ private unsafe String AllocateStringForNameIndex(int index, out int dataOffset) String s = null; char* charPtr = (char*)_ums.PositionPointer; -#if IA64 - if (((int)charPtr & 1) != 0) { - char[] destArray = new char[byteLen/2]; - fixed(char* pDest = destArray) { - Buffer.Memcpy((byte*)pDest, (byte*)charPtr, byteLen); - } - s = new String(destArray); - } - else { -#endif //IA64 + s = new String(charPtr, 0, byteLen / 2); -#if IA64 - } -#endif //IA64 + _ums.Position += byteLen; dataOffset = _store.ReadInt32(); if (dataOffset < 0 || dataOffset >= _store.BaseStream.Length - _dataSectionOffset) @@ -1057,7 +1045,6 @@ public void GetResourceData(String resourceName, out String resourceType, out by { if (resourceName == null) throw new ArgumentNullException(nameof(resourceName)); - Contract.EndContractBlock(); if (_resCache == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed); @@ -1122,7 +1109,7 @@ public void GetResourceData(String resourceName, out String resourceType, out by private String TypeNameFromTypeCode(ResourceTypeCode typeCode) { - Contract.Requires(typeCode >= 0, "can't be negative"); + Debug.Assert(typeCode >= 0, "can't be negative"); if (typeCode < ResourceTypeCode.StartOfUserTypes) { Debug.Assert(!String.Equals(typeCode.ToString(), "LastPrimitive"), "Change ResourceTypeCode metadata order so LastPrimitive isn't what Enum.ToString prefers."); diff --git a/src/mscorlib/src/System/Resources/ResourceSet.cs b/src/mscorlib/src/System/Resources/ResourceSet.cs index deb9763d5d91..9e5a72c43153 100644 --- a/src/mscorlib/src/System/Resources/ResourceSet.cs +++ b/src/mscorlib/src/System/Resources/ResourceSet.cs @@ -16,7 +16,6 @@ using System.Collections; using System.IO; using System.Reflection; -using System.Diagnostics.Contracts; namespace System.Resources { @@ -72,7 +71,6 @@ public ResourceSet(IResourceReader reader) { if (reader == null) throw new ArgumentNullException(nameof(reader)); - Contract.EndContractBlock(); Reader = reader; CommonInit(); ReadResources(); @@ -229,7 +227,6 @@ private Object GetObjectInternal(String name) { if (name == null) throw new ArgumentNullException(nameof(name)); - Contract.EndContractBlock(); Hashtable copyOfTable = Table; // Avoid a race with Dispose diff --git a/src/mscorlib/src/System/Resources/__FastResourceComparer.cs b/src/mscorlib/src/System/Resources/__FastResourceComparer.cs index 8bce02abc3ff..30d935ad5392 100644 --- a/src/mscorlib/src/System/Resources/__FastResourceComparer.cs +++ b/src/mscorlib/src/System/Resources/__FastResourceComparer.cs @@ -18,7 +18,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Resources { diff --git a/src/mscorlib/src/System/RtType.cs b/src/mscorlib/src/System/RtType.cs index 2d70354a48a8..e5bc0c5293fe 100644 --- a/src/mscorlib/src/System/RtType.cs +++ b/src/mscorlib/src/System/RtType.cs @@ -28,7 +28,6 @@ using DebuggerStepThroughAttribute = System.Diagnostics.DebuggerStepThroughAttribute; using MdToken = System.Reflection.MetadataToken; using System.Runtime.Versioning; -using System.Diagnostics.Contracts; namespace System { @@ -103,7 +102,7 @@ public T this[int index] { get { - Contract.Requires(index < Count); + Debug.Assert(index < Count); return (_items != null) ? _items[index] : _item; } } @@ -856,8 +855,8 @@ private unsafe void PopulateRtFields(Filter filter, RuntimeType declaringType, r private unsafe void PopulateRtFields(Filter filter, IntPtr* ppFieldHandles, int count, RuntimeType declaringType, ref ListBuilder list) { - Contract.Requires(declaringType != null); - Contract.Requires(ReflectedType != null); + Debug.Assert(declaringType != null); + Debug.Assert(ReflectedType != null); bool needsStaticFieldForGeneric = RuntimeTypeHandle.HasInstantiation(declaringType) && !RuntimeTypeHandle.ContainsGenericVariables(declaringType); bool isInherited = declaringType != ReflectedType; @@ -908,8 +907,8 @@ private unsafe void PopulateRtFields(Filter filter, private unsafe void PopulateLiteralFields(Filter filter, RuntimeType declaringType, ref ListBuilder list) { - Contract.Requires(declaringType != null); - Contract.Requires(ReflectedType != null); + Debug.Assert(declaringType != null); + Debug.Assert(ReflectedType != null); int tkDeclaringType = RuntimeTypeHandle.GetToken(declaringType); @@ -1127,7 +1126,7 @@ private unsafe RuntimeType[] PopulateNestedClasses(Filter filter) private unsafe RuntimeEventInfo[] PopulateEvents(Filter filter) { - Contract.Requires(ReflectedType != null); + Debug.Assert(ReflectedType != null); // Do not create the dictionary if we are filtering the properties by name already Dictionary csEventInfos = filter.CaseSensitive() ? null : @@ -1219,7 +1218,7 @@ private unsafe void PopulateEvents( private unsafe RuntimePropertyInfo[] PopulateProperties(Filter filter) { - Contract.Requires(ReflectedType != null); + Debug.Assert(ReflectedType != null); // m_csMemberInfos can be null at this point. It will be initialized when Insert // is called in Populate after this returns. @@ -1761,7 +1760,6 @@ internal static RuntimeType GetType(String typeName, bool throwOnError, bool ign { if (typeName == null) throw new ArgumentNullException(nameof(typeName)); - Contract.EndContractBlock(); return RuntimeTypeHandle.GetTypeByName( typeName, throwOnError, ignoreCase, reflectionOnly, ref stackMark, false); @@ -1975,7 +1973,7 @@ private unsafe static PropertyInfo GetPropertyInfo(RuntimeType reflectedType, in return property; } - Contract.Assume(false, "Unreachable code"); + Debug.Fail("Unreachable code"); throw new SystemException(); } @@ -1991,7 +1989,6 @@ internal static void SanityCheckGenericArguments(RuntimeType[] genericArguments, { if (genericArguments == null) throw new ArgumentNullException(); - Contract.EndContractBlock(); for (int i = 0; i < genericArguments.Length; i++) { @@ -2177,8 +2174,8 @@ private static bool FilterApplyBase( string name, bool prefixLookup) { #region Preconditions - Contract.Requires(memberInfo != null); - Contract.Requires(name == null || (bindingFlags & BindingFlags.IgnoreCase) == 0 || (name.ToLower(CultureInfo.InvariantCulture).Equals(name))); + Debug.Assert(memberInfo != null); + Debug.Assert(name == null || (bindingFlags & BindingFlags.IgnoreCase) == 0 || (name.ToLower(CultureInfo.InvariantCulture).Equals(name))); #endregion #region Filter by Public & Private @@ -2259,7 +2256,7 @@ private static bool FilterApplyBase( private static bool FilterApplyType( Type type, BindingFlags bindingFlags, string name, bool prefixLookup, string ns) { - Contract.Requires((object)type != null); + Debug.Assert((object)type != null); Debug.Assert(type is RuntimeType); bool isPublic = type.IsNestedPublic || type.IsPublic; @@ -2294,7 +2291,7 @@ private static bool FilterApplyConstructorInfo( private static bool FilterApplyMethodBase( MethodBase methodBase, BindingFlags methodFlags, BindingFlags bindingFlags, CallingConventions callConv, Type[] argumentTypes) { - Contract.Requires(methodBase != null); + Debug.Assert(methodBase != null); bindingFlags ^= BindingFlags.DeclaredOnly; @@ -2721,7 +2718,6 @@ public override InterfaceMapping GetInterfaceMap(Type ifaceType) if ((object)ifaceType == null) throw new ArgumentNullException(nameof(ifaceType)); - Contract.EndContractBlock(); RuntimeType ifaceRtType = ifaceType as RuntimeType; @@ -2864,7 +2860,6 @@ protected override PropertyInfo GetPropertyImpl( String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { if (name == null) throw new ArgumentNullException(); - Contract.EndContractBlock(); ListBuilder candidates = GetPropertyCandidates(name, bindingAttr, types, false); @@ -2904,7 +2899,6 @@ protected override PropertyInfo GetPropertyImpl( public override EventInfo GetEvent(String name, BindingFlags bindingAttr) { if (name == null) throw new ArgumentNullException(); - Contract.EndContractBlock(); bool ignoreCase; MemberListType listType; @@ -2933,7 +2927,6 @@ public override EventInfo GetEvent(String name, BindingFlags bindingAttr) public override FieldInfo GetField(String name, BindingFlags bindingAttr) { if (name == null) throw new ArgumentNullException(); - Contract.EndContractBlock(); bool ignoreCase; MemberListType listType; @@ -2973,7 +2966,6 @@ public override FieldInfo GetField(String name, BindingFlags bindingAttr) public override Type GetInterface(String fullname, bool ignoreCase) { if (fullname == null) throw new ArgumentNullException(); - Contract.EndContractBlock(); BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic; @@ -3009,7 +3001,6 @@ public override Type GetInterface(String fullname, bool ignoreCase) public override Type GetNestedType(String fullname, BindingFlags bindingAttr) { if (fullname == null) throw new ArgumentNullException(); - Contract.EndContractBlock(); bool ignoreCase; bindingAttr &= ~BindingFlags.Static; @@ -3040,7 +3031,6 @@ public override Type GetNestedType(String fullname, BindingFlags bindingAttr) public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { if (name == null) throw new ArgumentNullException(); - Contract.EndContractBlock(); ListBuilder methods = new ListBuilder(); ListBuilder constructors = new ListBuilder(); @@ -3233,7 +3223,6 @@ public override MethodBase DeclaringMethod { if (!IsGenericParameter) throw new InvalidOperationException(SR.Arg_NotGenericParameter); - Contract.EndContractBlock(); IRuntimeMethodInfo declaringMethod = RuntimeTypeHandle.GetDeclaringMethod(this); @@ -3251,12 +3240,10 @@ public override bool IsInstanceOfType(Object o) return RuntimeTypeHandle.IsInstanceOfType(this, o); } - [Pure] public override bool IsSubclassOf(Type type) { if ((object)type == null) throw new ArgumentNullException(nameof(type)); - Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; if (rtType == null) return false; @@ -3520,7 +3507,6 @@ public override GenericParameterAttributes GenericParameterAttributes { if (!IsGenericParameter) throw new InvalidOperationException(SR.Arg_NotGenericParameter); - Contract.EndContractBlock(); GenericParameterAttributes attributes; @@ -3577,7 +3563,6 @@ public override string[] GetEnumNames() { if (!IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, "enumType"); - Contract.EndContractBlock(); String[] ret = Enum.InternalGetNames(this); @@ -3593,7 +3578,6 @@ public override Array GetEnumValues() { if (!IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, "enumType"); - Contract.EndContractBlock(); // Get all of the values ulong[] values = Enum.InternalGetValues(this); @@ -3614,7 +3598,6 @@ public override Type GetEnumUnderlyingType() { if (!IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, "enumType"); - Contract.EndContractBlock(); return Enum.InternalGetUnderlyingType(this); } @@ -3623,7 +3606,6 @@ public override bool IsEnumDefined(object value) { if (value == null) throw new ArgumentNullException(nameof(value)); - Contract.EndContractBlock(); // Check if both of them are of the same type RuntimeType valueType = (RuntimeType)value.GetType(); @@ -3670,7 +3652,6 @@ public override string GetEnumName(object value) { if (value == null) throw new ArgumentNullException(nameof(value)); - Contract.EndContractBlock(); Type valueType = value.GetType(); @@ -3703,7 +3684,6 @@ public override Type MakeGenericType(Type[] instantiation) { if (instantiation == null) throw new ArgumentNullException(nameof(instantiation)); - Contract.EndContractBlock(); RuntimeType[] instantiationRuntimeType = new RuntimeType[instantiation.Length]; @@ -3778,7 +3758,6 @@ public override int GenericParameterPosition { if (!IsGenericParameter) throw new InvalidOperationException(SR.Arg_NotGenericParameter); - Contract.EndContractBlock(); return new RuntimeTypeHandle(this).GetGenericVariableIndex(); } @@ -3788,7 +3767,6 @@ public override Type GetGenericTypeDefinition() { if (!IsGenericType) throw new InvalidOperationException(SR.InvalidOperation_NotGenericType); - Contract.EndContractBlock(); return RuntimeTypeHandle.GetGenericTypeDefinition(this); } @@ -3812,7 +3790,6 @@ public override Type[] GetGenericParameterConstraints() { if (!IsGenericParameter) throw new InvalidOperationException(SR.Arg_NotGenericParameter); - Contract.EndContractBlock(); Type[] constraints = new RuntimeTypeHandle(this).GetConstraints(); @@ -3838,7 +3815,6 @@ public override Type MakeArrayType(int rank) { if (rank <= 0) throw new IndexOutOfRangeException(); - Contract.EndContractBlock(); return new RuntimeTypeHandle(this).MakeArray(rank); } @@ -4007,7 +3983,6 @@ public override Object InvokeMember( { if (IsGenericParameter) throw new InvalidOperationException(SR.Arg_GenericParameter); - Contract.EndContractBlock(); #region Preconditions if ((bindingFlags & InvocationMask) == 0) @@ -4455,7 +4430,6 @@ public override Object InvokeMember( #endregion #region Object Overrides - [Pure] public override bool Equals(object obj) { // ComObjects are identified by the instance of the Type object and not the TypeHandle. @@ -4490,7 +4464,6 @@ public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if ((object)attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; @@ -4504,7 +4477,6 @@ public override bool IsDefined(Type attributeType, bool inherit) { if ((object)attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; @@ -4617,7 +4589,6 @@ private void CreateInstanceCheckThis() if (ContainsGenericParameters) throw new ArgumentException( SR.Format(SR.Acc_CreateGenericEx, this)); - Contract.EndContractBlock(); Type elementType = this.GetRootElementType(); diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs index 0338b18beedb..b46c598ce3a1 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -21,7 +21,6 @@ namespace System.Runtime.CompilerServices using System.Runtime.Serialization; using System.Threading; using System.Runtime.Versioning; - using System.Diagnostics.Contracts; public static class RuntimeHelpers { diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs index 93bedd62b6f3..28305ba1a10d 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs @@ -40,7 +40,6 @@ using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.Contracts; using System.Security; using System.Threading; using System.Threading.Tasks; @@ -65,7 +64,7 @@ public struct TaskAwaiter : ICriticalNotifyCompletion /// The to be awaited. internal TaskAwaiter(Task task) { - Contract.Requires(task != null, "Constructing an awaiter requires a task to await."); + Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; } @@ -152,8 +151,8 @@ private static void HandleNonSuccessAndDebuggerNotification(Task task) /// Throws an exception to handle a task that completed in a state other than RanToCompletion. private static void ThrowForNonSuccess(Task task) { - Contract.Requires(task.IsCompleted, "Task must have been completed by now."); - Contract.Requires(task.Status != TaskStatus.RanToCompletion, "Task should not be completed successfully."); + Debug.Assert(task.IsCompleted, "Task must have been completed by now."); + Debug.Assert(task.Status != TaskStatus.RanToCompletion, "Task should not be completed successfully."); // Handle whether the task has been canceled or faulted switch (task.Status) @@ -220,8 +219,8 @@ internal static void OnCompletedInternal(Task task, Action continuation, bool co /// The action to use as the actual continuation. private static Action OutputWaitEtwEvents(Task task, Action continuation) { - Contract.Requires(task != null, "Need a task to wait on"); - Contract.Requires(continuation != null, "Need a continuation to invoke when the wait completes"); + Debug.Assert(task != null, "Need a task to wait on"); + Debug.Assert(continuation != null, "Need a continuation to invoke when the wait completes"); if (Task.s_asyncDebuggingEnabled) { @@ -299,7 +298,7 @@ public struct TaskAwaiter : ICriticalNotifyCompletion /// The to be awaited. internal TaskAwaiter(Task task) { - Contract.Requires(task != null, "Constructing an awaiter requires a task to await."); + Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; } @@ -357,7 +356,7 @@ public struct ConfiguredTaskAwaitable /// internal ConfiguredTaskAwaitable(Task task, bool continueOnCapturedContext) { - Contract.Requires(task != null, "Constructing an awaitable requires a task to await."); + Debug.Assert(task != null, "Constructing an awaitable requires a task to await."); m_configuredTaskAwaiter = new ConfiguredTaskAwaitable.ConfiguredTaskAwaiter(task, continueOnCapturedContext); } @@ -385,7 +384,7 @@ public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion /// internal ConfiguredTaskAwaiter(Task task, bool continueOnCapturedContext) { - Contract.Requires(task != null, "Constructing an awaiter requires a task to await."); + Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; m_continueOnCapturedContext = continueOnCapturedContext; } @@ -470,7 +469,7 @@ public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion /// internal ConfiguredTaskAwaiter(Task task, bool continueOnCapturedContext) { - Contract.Requires(task != null, "Constructing an awaiter requires a task to await."); + Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; m_continueOnCapturedContext = continueOnCapturedContext; } diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs index 929cbe760818..3e386fa8b7e6 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics.Contracts; namespace System.Runtime.CompilerServices { @@ -17,7 +16,6 @@ internal sealed class TypeDependencyAttribute : Attribute public TypeDependencyAttribute(string typeName) { if (typeName == null) throw new ArgumentNullException(nameof(typeName)); - Contract.EndContractBlock(); this.typeName = typeName; } } diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs b/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs index 3d9e6df673d4..8a7450bdb5d6 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs @@ -24,7 +24,6 @@ using System; using System.Security; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Diagnostics.Tracing; using System.Threading; using System.Threading.Tasks; @@ -77,7 +76,6 @@ private static void QueueContinuation(Action continuation, bool flowContext) { // Validate arguments if (continuation == null) throw new ArgumentNullException(nameof(continuation)); - Contract.EndContractBlock(); if (TplEtwProvider.Log.IsEnabled()) { diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs b/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs index b5f14af9cb7d..ef217d153f6c 100644 --- a/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs +++ b/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs @@ -12,7 +12,6 @@ using System.Runtime; using System.Runtime.Versioning; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Security; diff --git a/src/mscorlib/src/System/Runtime/GcSettings.cs b/src/mscorlib/src/System/Runtime/GcSettings.cs index ecb28e6034fe..6e08aa3dc5d9 100644 --- a/src/mscorlib/src/System/Runtime/GcSettings.cs +++ b/src/mscorlib/src/System/Runtime/GcSettings.cs @@ -6,7 +6,6 @@ using System; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; -using System.Diagnostics.Contracts; namespace System.Runtime { @@ -50,7 +49,6 @@ public static GCLatencyMode LatencyMode { throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Enum); } - Contract.EndContractBlock(); if (GC.SetGCLatencyMode((int)value) == (int)SetLatencyModeStatus.NoGCInProgress) throw new InvalidOperationException("The NoGCRegion mode is in progress. End it and then set a different mode."); @@ -72,7 +70,6 @@ public static GCLargeObjectHeapCompactionMode LargeObjectHeapCompactionMode { throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Enum); } - Contract.EndContractBlock(); GC.SetLOHCompactionMode((int)value); } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs index 7b50c705b26d..4570da9a93b0 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs @@ -8,7 +8,6 @@ using System; using System.Reflection; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Runtime.InteropServices { diff --git a/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs index 2ee81a9f5ca7..9b4670bfc0e0 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs @@ -7,7 +7,6 @@ namespace System.Runtime.InteropServices using System; using System.Runtime.CompilerServices; using System.Threading; - using System.Diagnostics.Contracts; #if BIT64 using nint = System.Int64; #else @@ -61,7 +60,6 @@ internal GCHandle(Object value, GCHandleType type) // Make sure the type parameter is within the valid range for the enum. if ((uint)type > (uint)MaxHandleType) ThrowArgumentOutOfRangeException_ArgumentOutOfRange_Enum(); - Contract.EndContractBlock(); IntPtr handle = InternalAlloc(value, type); @@ -160,7 +158,6 @@ public static explicit operator GCHandle(IntPtr value) public static GCHandle FromIntPtr(IntPtr value) { ValidateHandle(value); - Contract.EndContractBlock(); #if MDA_SUPPORTED IntPtr handle = value; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs index 4ce4cc3d343e..39624c192821 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs @@ -29,7 +29,6 @@ namespace System.Runtime.InteropServices using Win32Native = Microsoft.Win32.Win32Native; using Microsoft.Win32.SafeHandles; using System.Diagnostics; - using System.Diagnostics.Contracts; using System.Runtime.InteropServices.ComTypes; using System.StubHelpers; @@ -231,7 +230,6 @@ public static int SizeOf(Object structure) if (structure == null) throw new ArgumentNullException(nameof(structure)); // we never had a check for generics here - Contract.EndContractBlock(); return SizeOfHelper(structure.GetType(), true); } @@ -241,7 +239,6 @@ public static int SizeOf(T structure) return SizeOf((object)structure); } - [Pure] public static int SizeOf(Type t) { if (t == null) @@ -250,7 +247,6 @@ public static int SizeOf(Type t) throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t)); if (t.IsGenericType) throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t)); - Contract.EndContractBlock(); return SizeOfHelper(t, true); } @@ -299,7 +295,6 @@ public static IntPtr OffsetOf(Type t, String fieldName) { if (t == null) throw new ArgumentNullException(nameof(t)); - Contract.EndContractBlock(); FieldInfo f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (f == null) @@ -871,7 +866,6 @@ public static void Prelink(MethodInfo m) { if (m == null) throw new ArgumentNullException(nameof(m)); - Contract.EndContractBlock(); RuntimeMethodInfo rmi = m as RuntimeMethodInfo; @@ -888,7 +882,6 @@ public static void PrelinkAll(Type c) { if (c == null) throw new ArgumentNullException(nameof(c)); - Contract.EndContractBlock(); MethodInfo[] mi = c.GetMethods(); if (mi != null) @@ -991,7 +984,6 @@ public static IntPtr GetHINSTANCE(Module m) { if (m == null) throw new ArgumentNullException(nameof(m)); - Contract.EndContractBlock(); RuntimeModule rtModule = m as RuntimeModule; if (rtModule == null) @@ -1203,7 +1195,6 @@ public static String GetTypeInfoName(ITypeInfo typeInfo) { if (typeInfo == null) throw new ArgumentNullException(nameof(typeInfo)); - Contract.EndContractBlock(); String strTypeLibName = null; String strDocString = null; @@ -1519,7 +1510,6 @@ public static Int32 FinalReleaseComObject(Object o) { if (o == null) throw new ArgumentNullException(nameof(o)); - Contract.EndContractBlock(); __ComObject co = null; @@ -1575,7 +1565,6 @@ public static Object CreateWrapperOfType(Object o, Type t) throw new ArgumentException(SR.Argument_TypeNotComObject, nameof(t)); if (t.IsGenericType) throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t)); - Contract.EndContractBlock(); if (t.IsWindowsRuntimeObject) throw new ArgumentException(SR.Argument_TypeIsWinRTType, nameof(t)); @@ -1701,7 +1690,6 @@ public static String GenerateProgIdForType(Type type) throw new ArgumentException(SR.Argument_TypeMustNotBeComImport, nameof(type)); if (type.IsGenericType) throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type)); - Contract.EndContractBlock(); IList cas = CustomAttributeData.GetCustomAttributes(type); for (int i = 0; i < cas.Count; i++) @@ -1798,7 +1786,6 @@ public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t) if (t == null) throw new ArgumentNullException(nameof(t)); - Contract.EndContractBlock(); if ((t as RuntimeType) == null) throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t)); @@ -1825,7 +1812,6 @@ public static IntPtr GetFunctionPointerForDelegate(Delegate d) { if (d == null) throw new ArgumentNullException(nameof(d)); - Contract.EndContractBlock(); return GetFunctionPointerForDelegateInternal(d); } @@ -1844,7 +1830,6 @@ public static IntPtr SecureStringToBSTR(SecureString s) { throw new ArgumentNullException(nameof(s)); } - Contract.EndContractBlock(); return s.MarshalToBSTR(); } @@ -1855,7 +1840,6 @@ public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s) { throw new ArgumentNullException(nameof(s)); } - Contract.EndContractBlock(); return s.MarshalToString(globalAlloc: false, unicode: false); } @@ -1866,7 +1850,6 @@ public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s) { throw new ArgumentNullException(nameof(s)); } - Contract.EndContractBlock(); return s.MarshalToString(globalAlloc: false, unicode: true); } @@ -1901,7 +1884,6 @@ public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s) { throw new ArgumentNullException(nameof(s)); } - Contract.EndContractBlock(); return s.MarshalToString(globalAlloc: true, unicode: false); } @@ -1912,7 +1894,6 @@ public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s) { throw new ArgumentNullException(nameof(s)); } - Contract.EndContractBlock(); return s.MarshalToString(globalAlloc: true, unicode: true); ; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs index 6e6d6ee2b64e..4f9787547019 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs @@ -73,7 +73,6 @@ using System.Runtime.Versioning; using Microsoft.Win32.SafeHandles; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Runtime.InteropServices { @@ -100,7 +99,6 @@ public void Initialize(ulong numBytes) { if (IntPtr.Size == 4 && numBytes > UInt32.MaxValue) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_AddressSpace); - Contract.EndContractBlock(); if (numBytes >= (ulong)Uninitialized) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_UIntPtrMax); @@ -117,7 +115,6 @@ public void Initialize(uint numElements, uint sizeOfEachElement) { if (IntPtr.Size == 4 && numElements * sizeOfEachElement > UInt32.MaxValue) throw new ArgumentOutOfRangeException("numBytes", SR.ArgumentOutOfRange_AddressSpace); - Contract.EndContractBlock(); if (numElements * sizeOfEachElement >= (ulong)Uninitialized) throw new ArgumentOutOfRangeException(nameof(numElements), SR.ArgumentOutOfRange_UIntPtrMax); @@ -235,7 +232,6 @@ public void ReadArray(ulong byteOffset, T[] array, int index, int count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.EndContractBlock(); if (_numBytes == Uninitialized) throw NotInitialized(); @@ -306,7 +302,6 @@ public void WriteArray(ulong byteOffset, T[] array, int index, int count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); - Contract.EndContractBlock(); if (_numBytes == Uninitialized) throw NotInitialized(); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs index 88b60583f5fb..014e63e89d71 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs @@ -10,7 +10,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -32,7 +31,6 @@ private BindableVectorToCollectionAdapter() } // int Count { get } - [Pure] internal int Count() { IBindableVector _this = Unsafe.As(this); @@ -46,21 +44,18 @@ internal int Count() } // bool IsSynchronized { get } - [Pure] internal bool IsSynchronized() { return false; } // object SyncRoot { get } - [Pure] internal object SyncRoot() { return this; } // void CopyTo(Array array, int index) - [Pure] internal void CopyTo(Array array, int arrayIndex) { if (array == null) diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs index 655dcbd3bcaf..122c7a1b137f 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs @@ -10,7 +10,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -83,14 +82,12 @@ internal void Clear() } // bool IsFixedSize { get } - [Pure] internal bool IsFixedSize() { return false; } // bool IsReadOnly { get } - [Pure] internal bool IsReadOnly() { return false; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs index 86321e6191dd..92c78f9ea2d5 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs @@ -6,7 +6,7 @@ using System; using System.Collections.Generic; -using System.Diagnostics.Contracts; +using System.Diagnostics; namespace System.Runtime.InteropServices.WindowsRuntime { @@ -22,13 +22,11 @@ public CLRIKeyValuePairImpl([In] ref KeyValuePair pair) } // IKeyValuePair implementation - [Pure] public K Key { get { return _pair.Key; } } - [Pure] public V Value { get { return _pair.Value; } @@ -37,7 +35,7 @@ public V Value // Called from the VM to wrap a boxed KeyValuePair with a CLRIKeyValuePairImpl. internal static object BoxHelper(object pair) { - Contract.Requires(pair != null); + Debug.Assert(pair != null); KeyValuePair unboxedPair = (KeyValuePair)pair; return new CLRIKeyValuePairImpl(ref unboxedPair); @@ -46,7 +44,7 @@ internal static object BoxHelper(object pair) // Called from the VM to get a boxed KeyValuePair out of a CLRIKeyValuePairImpl. internal static object UnboxHelper(object wrapper) { - Contract.Requires(wrapper != null); + Debug.Assert(wrapper != null); CLRIKeyValuePairImpl reference = (CLRIKeyValuePairImpl)wrapper; return reference._pair; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs index 75774caae2a4..12c77a22540f 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs @@ -5,7 +5,7 @@ // using System; -using System.Diagnostics.Contracts; +using System.Diagnostics; using System.Runtime.CompilerServices; using System.Security; @@ -52,13 +52,11 @@ private static Tuple[] NumericScalarTypes public PropertyType Type { - [Pure] get { return _type; } } public bool IsNumericScalar { - [Pure] get { return IsNumericScalarImpl(_type, _data); @@ -77,13 +75,11 @@ public override string ToString() } } - [Pure] public Byte GetUInt8() { return CoerceScalarValue(PropertyType.UInt8); } - [Pure] public Int16 GetInt16() { return CoerceScalarValue(PropertyType.Int16); @@ -94,260 +90,211 @@ public UInt16 GetUInt16() return CoerceScalarValue(PropertyType.UInt16); } - [Pure] public Int32 GetInt32() { return CoerceScalarValue(PropertyType.Int32); } - [Pure] public UInt32 GetUInt32() { return CoerceScalarValue(PropertyType.UInt32); } - [Pure] public Int64 GetInt64() { return CoerceScalarValue(PropertyType.Int64); } - [Pure] public UInt64 GetUInt64() { return CoerceScalarValue(PropertyType.UInt64); } - [Pure] public Single GetSingle() { return CoerceScalarValue(PropertyType.Single); } - [Pure] public Double GetDouble() { return CoerceScalarValue(PropertyType.Double); } - [Pure] public char GetChar16() { if (this.Type != PropertyType.Char16) throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Char16"), HResults.TYPE_E_TYPEMISMATCH); - Contract.EndContractBlock(); return (char)_data; } - [Pure] public Boolean GetBoolean() { if (this.Type != PropertyType.Boolean) throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Boolean"), HResults.TYPE_E_TYPEMISMATCH); - Contract.EndContractBlock(); return (bool)_data; } - [Pure] public String GetString() { return CoerceScalarValue(PropertyType.String); } - [Pure] public Guid GetGuid() { return CoerceScalarValue(PropertyType.Guid); } - [Pure] public DateTimeOffset GetDateTime() { if (this.Type != PropertyType.DateTime) throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "DateTime"), HResults.TYPE_E_TYPEMISMATCH); - Contract.EndContractBlock(); return (DateTimeOffset)_data; } - [Pure] public TimeSpan GetTimeSpan() { if (this.Type != PropertyType.TimeSpan) throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "TimeSpan"), HResults.TYPE_E_TYPEMISMATCH); - Contract.EndContractBlock(); return (TimeSpan)_data; } - [Pure] public Point GetPoint() { if (this.Type != PropertyType.Point) throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Point"), HResults.TYPE_E_TYPEMISMATCH); - Contract.EndContractBlock(); return Unbox(IReferenceFactory.s_pointType); } - [Pure] public Size GetSize() { if (this.Type != PropertyType.Size) throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Size"), HResults.TYPE_E_TYPEMISMATCH); - Contract.EndContractBlock(); return Unbox(IReferenceFactory.s_sizeType); } - [Pure] public Rect GetRect() { if (this.Type != PropertyType.Rect) throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Rect"), HResults.TYPE_E_TYPEMISMATCH); - Contract.EndContractBlock(); return Unbox(IReferenceFactory.s_rectType); } - [Pure] public Byte[] GetUInt8Array() { return CoerceArrayValue(PropertyType.UInt8Array); } - [Pure] public Int16[] GetInt16Array() { return CoerceArrayValue(PropertyType.Int16Array); } - [Pure] public UInt16[] GetUInt16Array() { return CoerceArrayValue(PropertyType.UInt16Array); } - [Pure] public Int32[] GetInt32Array() { return CoerceArrayValue(PropertyType.Int32Array); } - [Pure] public UInt32[] GetUInt32Array() { return CoerceArrayValue(PropertyType.UInt32Array); } - [Pure] public Int64[] GetInt64Array() { return CoerceArrayValue(PropertyType.Int64Array); } - [Pure] public UInt64[] GetUInt64Array() { return CoerceArrayValue(PropertyType.UInt64Array); } - [Pure] public Single[] GetSingleArray() { return CoerceArrayValue(PropertyType.SingleArray); } - [Pure] public Double[] GetDoubleArray() { return CoerceArrayValue(PropertyType.DoubleArray); } - [Pure] public char[] GetChar16Array() { if (this.Type != PropertyType.Char16Array) throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Char16[]"), HResults.TYPE_E_TYPEMISMATCH); - Contract.EndContractBlock(); return (char[])_data; } - [Pure] public Boolean[] GetBooleanArray() { if (this.Type != PropertyType.BooleanArray) throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Boolean[]"), HResults.TYPE_E_TYPEMISMATCH); - Contract.EndContractBlock(); return (bool[])_data; } - [Pure] public String[] GetStringArray() { return CoerceArrayValue(PropertyType.StringArray); } - [Pure] public Object[] GetInspectableArray() { if (this.Type != PropertyType.InspectableArray) throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Inspectable[]"), HResults.TYPE_E_TYPEMISMATCH); - Contract.EndContractBlock(); return (Object[])_data; } - [Pure] public Guid[] GetGuidArray() { return CoerceArrayValue(PropertyType.GuidArray); } - [Pure] public DateTimeOffset[] GetDateTimeArray() { if (this.Type != PropertyType.DateTimeArray) throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "DateTimeOffset[]"), HResults.TYPE_E_TYPEMISMATCH); - Contract.EndContractBlock(); return (DateTimeOffset[])_data; } - [Pure] public TimeSpan[] GetTimeSpanArray() { if (this.Type != PropertyType.TimeSpanArray) throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "TimeSpan[]"), HResults.TYPE_E_TYPEMISMATCH); - Contract.EndContractBlock(); return (TimeSpan[])_data; } - [Pure] public Point[] GetPointArray() { if (this.Type != PropertyType.PointArray) throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Point[]"), HResults.TYPE_E_TYPEMISMATCH); - Contract.EndContractBlock(); return UnboxArray(IReferenceFactory.s_pointType); } - [Pure] public Size[] GetSizeArray() { if (this.Type != PropertyType.SizeArray) throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Size[]"), HResults.TYPE_E_TYPEMISMATCH); - Contract.EndContractBlock(); return UnboxArray(IReferenceFactory.s_sizeType); } - [Pure] public Rect[] GetRectArray() { if (this.Type != PropertyType.RectArray) throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Rect[]"), HResults.TYPE_E_TYPEMISMATCH); - Contract.EndContractBlock(); return UnboxArray(IReferenceFactory.s_rectType); } @@ -531,11 +478,10 @@ private static bool IsNumericScalarImpl(PropertyType type, object data) } // Unbox the data stored in the property value to a structurally equivilent type - [Pure] private unsafe T Unbox(Type expectedBoxedType) where T : struct { - Contract.Requires(expectedBoxedType != null); - Contract.Requires(Marshal.SizeOf(expectedBoxedType) == Marshal.SizeOf(typeof(T))); + Debug.Assert(expectedBoxedType != null); + Debug.Assert(Marshal.SizeOf(expectedBoxedType) == Marshal.SizeOf(typeof(T))); if (_data.GetType() != expectedBoxedType) { @@ -554,11 +500,10 @@ private unsafe T Unbox(Type expectedBoxedType) where T : struct } // Convert the array stored in the property value to a structurally equivilent array type - [Pure] private unsafe T[] UnboxArray(Type expectedArrayElementType) where T : struct { - Contract.Requires(expectedArrayElementType != null); - Contract.Requires(Marshal.SizeOf(expectedArrayElementType) == Marshal.SizeOf(typeof(T))); + Debug.Assert(expectedArrayElementType != null); + Debug.Assert(Marshal.SizeOf(expectedArrayElementType) == Marshal.SizeOf(typeof(T))); Array dataArray = _data as Array; if (dataArray == null || _data.GetType().GetElementType() != expectedArrayElementType) diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs index 3afd87ab127a..d8fa4b3cae5d 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs @@ -7,7 +7,6 @@ using System; using System.Collections; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Reflection; using System.Security; @@ -55,7 +54,7 @@ object IGetProxyTarget.GetTarget() [System.Runtime.CompilerServices.FriendAccessAllowed] internal static Object UnboxHelper(Object wrapper) { - Contract.Requires(wrapper != null); + Debug.Assert(wrapper != null); IReference reference = (IReference)wrapper; Debug.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<" + typeof(T) + ">, but that failed."); return reference.Value; @@ -218,7 +217,7 @@ object IGetProxyTarget.GetTarget() [System.Runtime.CompilerServices.FriendAccessAllowed] internal static Object UnboxHelper(Object wrapper) { - Contract.Requires(wrapper != null); + Debug.Assert(wrapper != null); IReferenceArray reference = (IReferenceArray)wrapper; Debug.Assert(reference != null, "CLRIReferenceArrayImpl::UnboxHelper - QI'ed for IReferenceArray<" + typeof(T) + ">, but that failed."); T[] marshaled = reference.Value; @@ -235,8 +234,7 @@ internal static class IReferenceFactory internal static Object CreateIReference(Object obj) { - Contract.Requires(obj != null, "Null should not be boxed."); - Contract.Ensures(Contract.Result() != null); + Debug.Assert(obj != null, "Null should not be boxed."); Type type = obj.GetType(); @@ -311,9 +309,8 @@ internal static Object CreateIReference(Object obj) internal static Object CreateIReferenceArray(Array obj) { - Contract.Requires(obj != null); - Contract.Requires(obj.GetType().IsArray); - Contract.Ensures(Contract.Result() != null); + Debug.Assert(obj != null); + Debug.Assert(obj.GetType().IsArray); Type type = obj.GetType().GetElementType(); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs index 6ec39b990268..188d1033b3c7 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs @@ -45,7 +45,6 @@ internal ConstantSplittableMap(IReadOnlyDictionary data) { if (data == null) throw new ArgumentNullException(nameof(data)); - Contract.EndContractBlock(); firstItemIndex = 0; lastItemIndex = data.Count - 1; @@ -177,11 +176,11 @@ internal struct IKeyValuePairEnumerator : IEnumerator[] items, int first, int end) { - Contract.Requires(items != null); - Contract.Requires(first >= 0); - Contract.Requires(end >= 0); - Contract.Requires(first < items.Length); - Contract.Requires(end < items.Length); + Debug.Assert(items != null); + Debug.Assert(first >= 0); + Debug.Assert(end >= 0); + Debug.Assert(first < items.Length); + Debug.Assert(end < items.Length); _array = items; _start = first; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs index 63565a39b882..ae58844273e1 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs @@ -8,7 +8,6 @@ using System.Security; using System.Reflection; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Serialization; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs index 6325966f82e9..5d9f332a61b2 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs @@ -11,7 +11,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs index 6be0ddd9f01f..d441a2fbf84a 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs @@ -6,7 +6,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.InteropServices.WindowsRuntime; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs index e7bc95ead481..95158b093d1a 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs @@ -8,7 +8,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -74,7 +73,7 @@ internal sealed class EnumeratorToIteratorAdapter : IIterator, IBindableIt internal EnumeratorToIteratorAdapter(IEnumerator enumerator) { - Contract.Requires(enumerator != null); + Debug.Assert(enumerator != null); m_enumerator = enumerator; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs index 974da48a425d..2ecd4181dbc2 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs @@ -6,7 +6,7 @@ using System; using System.Collections.Generic; -using System.Diagnostics.Contracts; +using System.Diagnostics; using System.Threading; namespace System.Runtime.InteropServices.WindowsRuntime @@ -73,7 +73,7 @@ public EventRegistrationToken AddEventHandler(T handler) private EventRegistrationToken AddEventHandlerNoLock(T handler) { - Contract.Requires(handler != null); + Debug.Assert(handler != null); // Get a registration token, making sure that we haven't already used the value. This should be quite // rare, but in the case it does happen, just keep trying until we find one that's unused. @@ -127,7 +127,7 @@ internal T ExtractHandler(EventRegistrationToken token) // 2. Use it as a guess to quickly see if the handler was really assigned this token value private static EventRegistrationToken GetPreferredToken(T handler) { - Contract.Requires(handler != null); + Debug.Assert(handler != null); // We want to generate a token value that has the following properties: // 1. is quickly obtained from the handler instance diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs index b7cd87acfc1c..564b86e685ed 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs @@ -8,7 +8,6 @@ using System.Security; using System.Collections; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs index 3ff4ffd09816..07fb8f171a3b 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs @@ -5,7 +5,6 @@ // using System; -using System.Diagnostics.Contracts; namespace System.Runtime.InteropServices.WindowsRuntime { @@ -16,35 +15,29 @@ internal interface ICustomProperty { Type Type { - [Pure] get; } string Name { - [Pure] get; } - [Pure] object GetValue(object target); void SetValue(object target, object value); - [Pure] object GetValue(object target, object indexValue); void SetValue(object target, object value, object indexValue); bool CanWrite { - [Pure] get; } bool CanRead { - [Pure] get; } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs index 0c9fc3609b08..bbe4d5e734b3 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs @@ -7,7 +7,7 @@ using System; using System.StubHelpers; using System.Reflection; -using System.Diagnostics.Contracts; +using System.Diagnostics; using System.Runtime.InteropServices; using System.Collections; using System.Collections.Generic; @@ -27,8 +27,8 @@ internal static class ICustomPropertyProviderImpl // static internal ICustomProperty CreateProperty(object target, string propertyName) { - Contract.Requires(target != null); - Contract.Requires(propertyName != null); + Debug.Assert(target != null); + Debug.Assert(propertyName != null); IGetProxyTarget proxy = target as IGetProxyTarget; if (proxy != null) @@ -51,8 +51,8 @@ static internal ICustomProperty CreateProperty(object target, string propertyNam // static internal unsafe ICustomProperty CreateIndexedProperty(object target, string propertyName, TypeNameNative* pIndexedParamType) { - Contract.Requires(target != null); - Contract.Requires(propertyName != null); + Debug.Assert(target != null); + Debug.Assert(propertyName != null); Type indexedParamType = null; SystemTypeMarshaler.ConvertToManaged(pIndexedParamType, ref indexedParamType); @@ -62,8 +62,8 @@ static internal unsafe ICustomProperty CreateIndexedProperty(object target, stri static internal ICustomProperty CreateIndexedProperty(object target, string propertyName, Type indexedParamType) { - Contract.Requires(target != null); - Contract.Requires(propertyName != null); + Debug.Assert(target != null); + Debug.Assert(propertyName != null); IGetProxyTarget proxy = target as IGetProxyTarget; if (proxy != null) @@ -243,7 +243,6 @@ public IEnumerator GetEnumerator() // // IBindableVector implementation (forwards to IBindableVector / IVector) // - [Pure] object IBindableVector.GetAt(uint index) { IBindableVector bindableVector = GetIBindableVectorNoThrow(); @@ -259,7 +258,6 @@ object IBindableVector.GetAt(uint index) } } - [Pure] uint IBindableVector.Size { get @@ -278,7 +276,6 @@ uint IBindableVector.Size } } - [Pure] IBindableVectorView IBindableVector.GetView() { IBindableVector bindableVector = GetIBindableVectorNoThrow(); @@ -303,13 +300,11 @@ public IVectorViewToIBindableVectorViewAdapter(IVectorView vectorView) _vectorView = vectorView; } - [Pure] object IBindableVectorView.GetAt(uint index) { return _vectorView.GetAt(index); } - [Pure] uint IBindableVectorView.Size { get @@ -318,7 +313,6 @@ uint IBindableVectorView.Size } } - [Pure] bool IBindableVectorView.IndexOf(object value, out uint index) { return _vectorView.IndexOf(ConvertTo(value), out index); @@ -330,7 +324,6 @@ IBindableIterator IBindableIterable.First() } } - [Pure] bool IBindableVector.IndexOf(object value, out uint index) { IBindableVector bindableVector = GetIBindableVectorNoThrow(); @@ -456,7 +449,6 @@ private IVector_Raw GetVectorOfT() // // IBindableVectorView implementation (forwarding to IBindableVectorView or IVectorView) // - [Pure] object IBindableVectorView.GetAt(uint index) { IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow(); @@ -466,7 +458,6 @@ object IBindableVectorView.GetAt(uint index) return GetVectorViewOfT().GetAt(index); } - [Pure] uint IBindableVectorView.Size { get @@ -479,7 +470,6 @@ uint IBindableVectorView.Size } } - [Pure] bool IBindableVectorView.IndexOf(object value, out uint index) { IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow(); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs index 30ce8954232c..a44591245f3d 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics.Contracts; // Windows.Foundation.Collections.IIterable`1 cannot be referenced from managed code because it's hidden // by the metadata adapter. We redeclare the interface manually to be able to talk to native WinRT objects. @@ -18,7 +17,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime [WindowsRuntimeImport] internal interface IIterable : IEnumerable { - [Pure] IIterator First(); } @@ -27,7 +25,6 @@ internal interface IIterable : IEnumerable [WindowsRuntimeImport] internal interface IBindableIterable { - [Pure] IBindableIterator First(); } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IIterator.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IIterator.cs index 83817494df85..00d622b711bf 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IIterator.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IIterator.cs @@ -5,7 +5,6 @@ // using System; -using System.Diagnostics.Contracts; namespace System.Runtime.InteropServices.WindowsRuntime { @@ -14,13 +13,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime [Guid("6a79e863-4300-459a-9966-cbb660963ee1")] internal interface IIterator { - [Pure] T Current { get; } - [Pure] bool HasCurrent { get; @@ -28,7 +25,6 @@ bool HasCurrent bool MoveNext(); - [Pure] int GetMany([Out] T[] items); } @@ -37,13 +33,11 @@ bool HasCurrent [Guid("6a1d6c07-076d-49f2-8314-f52c9c9a8331")] internal interface IBindableIterator { - [Pure] object Current { get; } - [Pure] bool HasCurrent { get; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs index 1f954a66b0f4..02dff54eac4e 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics.Contracts; // Windows.Foundation.Collections.IMap`2, IMapView`2, and IKeyValuePair`2 cannot be referenced from // managed code because they're hidden by the metadata adapter. We redeclare the interfaces manually @@ -19,13 +18,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime [WindowsRuntimeImport] internal interface IMap : IIterable> { - [Pure] V Lookup(K key); - [Pure] uint Size { get; } - [Pure] bool HasKey(K key); - [Pure] IReadOnlyDictionary GetView(); // Really an IMapView bool Insert(K key, V value); void Remove(K key); @@ -37,13 +32,9 @@ internal interface IMap : IIterable> [WindowsRuntimeImport] internal interface IMapView : IIterable> { - [Pure] V Lookup(K key); - [Pure] uint Size { get; } - [Pure] bool HasKey(K key); - [Pure] void Split(out IMapView first, out IMapView second); } @@ -52,9 +43,7 @@ internal interface IMapView : IIterable> [WindowsRuntimeImport] internal interface IKeyValuePair { - [Pure] K Key { get; } - [Pure] V Value { get; } } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs index f309cfd0d8ec..aa7bf76750d0 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs @@ -9,7 +9,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -36,7 +35,6 @@ internal V Indexer_Get(K key) { if (key == null) throw new ArgumentNullException(nameof(key)); - Contract.EndContractBlock(); IMapView _this = Unsafe.As>(this); return Lookup(_this, key); @@ -59,7 +57,6 @@ internal IEnumerable Values() } // bool ContainsKey(K key) - [Pure] internal bool ContainsKey(K key) { if (key == null) @@ -105,7 +102,7 @@ internal bool TryGetValue(K key, out V value) private static V Lookup(IMapView _this, K key) { - Contract.Requires(null != key); + Debug.Assert(null != key); try { diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs index a2b07b2ea73b..8a67119496f2 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs @@ -5,7 +5,6 @@ // using System; -using System.Diagnostics.Contracts; namespace System.Runtime.InteropServices.WindowsRuntime { @@ -16,125 +15,86 @@ internal interface IPropertyValue { PropertyType Type { - [Pure] get; } bool IsNumericScalar { - [Pure] get; } - [Pure] Byte GetUInt8(); - [Pure] Int16 GetInt16(); - [Pure] UInt16 GetUInt16(); - [Pure] Int32 GetInt32(); - [Pure] UInt32 GetUInt32(); - [Pure] Int64 GetInt64(); - [Pure] UInt64 GetUInt64(); - [Pure] Single GetSingle(); - [Pure] Double GetDouble(); - [Pure] char GetChar16(); - [Pure] Boolean GetBoolean(); - [Pure] String GetString(); - [Pure] Guid GetGuid(); - [Pure] DateTimeOffset GetDateTime(); - [Pure] TimeSpan GetTimeSpan(); - [Pure] Point GetPoint(); - [Pure] Size GetSize(); - [Pure] Rect GetRect(); - [Pure] Byte[] GetUInt8Array(); - [Pure] Int16[] GetInt16Array(); - [Pure] UInt16[] GetUInt16Array(); - [Pure] Int32[] GetInt32Array(); - [Pure] UInt32[] GetUInt32Array(); - [Pure] Int64[] GetInt64Array(); - [Pure] UInt64[] GetUInt64Array(); - [Pure] Single[] GetSingleArray(); - [Pure] Double[] GetDoubleArray(); - [Pure] char[] GetChar16Array(); - [Pure] Boolean[] GetBooleanArray(); - [Pure] String[] GetStringArray(); - [Pure] object[] GetInspectableArray(); - [Pure] Guid[] GetGuidArray(); - [Pure] DateTimeOffset[] GetDateTimeArray(); - [Pure] TimeSpan[] GetTimeSpanArray(); - [Pure] Point[] GetPointArray(); - [Pure] Size[] GetSizeArray(); - [Pure] Rect[] GetRectArray(); } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs index ef9959b764fb..f5bc58a7e547 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs @@ -9,7 +9,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs index a3e7b868eeb9..c69115d1eb17 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs @@ -9,7 +9,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs index e88f4f3b9f78..f00a7d350450 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics.Contracts; // Windows.Foundation.Collections.IVector`1 and IVectorView`1 cannot be referenced from managed // code because they're hidden by the metadata adapter. We redeclare the interfaces manually @@ -19,13 +18,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime [WindowsRuntimeImport] internal interface IVector : IIterable { - [Pure] T GetAt(uint index); - [Pure] uint Size { get; } - [Pure] IReadOnlyList GetView(); // Really an IVectorView. - [Pure] bool IndexOf(T value, out uint index); void SetAt(uint index, T value); void InsertAt(uint index, T value); @@ -33,7 +28,6 @@ internal interface IVector : IIterable void Append(T value); void RemoveAtEnd(); void Clear(); - [Pure] uint GetMany(uint startIndex, [Out] T[] items); void ReplaceAll(T[] items); } @@ -44,13 +38,9 @@ internal interface IVector : IIterable [WindowsRuntimeImport] internal interface IVector_Raw : IIterable { - [Pure] T GetAt(uint index); - [Pure] uint Size { get; } - [Pure] IVectorView GetView(); - [Pure] bool IndexOf(T value, out uint index); void SetAt(uint index, T value); void InsertAt(uint index, T value); @@ -65,13 +55,9 @@ internal interface IVector_Raw : IIterable [WindowsRuntimeImport] internal interface IVectorView : IIterable { - [Pure] T GetAt(uint index); - [Pure] uint Size { get; } - [Pure] bool IndexOf(T value, out uint index); - [Pure] uint GetMany(uint startIndex, [Out] T[] items); } @@ -80,13 +66,9 @@ internal interface IVectorView : IIterable [WindowsRuntimeImport] internal interface IBindableVector : IBindableIterable { - [Pure] object GetAt(uint index); - [Pure] uint Size { get; } - [Pure] IBindableVectorView GetView(); - [Pure] bool IndexOf(object value, out uint index); void SetAt(uint index, object value); void InsertAt(uint index, object value); @@ -101,11 +83,8 @@ internal interface IBindableVector : IBindableIterable [WindowsRuntimeImport] internal interface IBindableVectorView : IBindableIterable { - [Pure] object GetAt(uint index); - [Pure] uint Size { get; } - [Pure] bool IndexOf(object value, out uint index); } } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs index 1a5f291da87e..144567068066 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs @@ -9,7 +9,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs index 321dba2ab03e..7bc2fa06a97c 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs @@ -8,7 +8,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Security; @@ -109,7 +108,7 @@ internal sealed class IteratorToEnumeratorAdapter : IEnumerator internal IteratorToEnumeratorAdapter(IIterator iterator) { - Contract.Requires(iterator != null); + Debug.Assert(iterator != null); m_iterator = iterator; m_hadCurrent = true; m_isInitialized = false; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs index 5ba5e1e2ec60..c0c8769b5a32 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs @@ -11,7 +11,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs index 75c9b9d086b3..e92b879b1da5 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs @@ -10,7 +10,6 @@ using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -27,7 +26,6 @@ internal ListToBindableVectorViewAdapter(IList list) if (list == null) throw new ArgumentNullException(nameof(list)); - Contract.EndContractBlock(); this.list = list; } diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs index f138bcbae804..4f23f639f2bb 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs @@ -11,7 +11,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs index 12b13ac79b8d..82ef71c783fd 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs @@ -5,7 +5,6 @@ // using System; -using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.InteropServices; using System.Security; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs index 11ed78676f1a..8cc189b162d8 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs @@ -9,7 +9,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -34,7 +33,6 @@ private MapToCollectionAdapter() } // int Count { get } - [Pure] internal int Count() { object _this = Unsafe.As(this); @@ -145,7 +143,6 @@ internal void CopyTo(KeyValuePair[] array, int arrayIndex) if (array.Length - arrayIndex < Count()) throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); - Contract.EndContractBlock(); IIterable> _this = Unsafe.As>>(this); foreach (KeyValuePair mapping in _this) diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs index 296b453b85ef..a69acb7eeb69 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs @@ -9,7 +9,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -36,7 +35,6 @@ internal V Indexer_Get(K key) if (key == null) throw new ArgumentNullException(nameof(key)); - Contract.EndContractBlock(); IMap _this = Unsafe.As>(this); return Lookup(_this, key); @@ -48,7 +46,6 @@ internal void Indexer_Set(K key, V value) if (key == null) throw new ArgumentNullException(nameof(key)); - Contract.EndContractBlock(); IMap _this = Unsafe.As>(this); Insert(_this, key, value); @@ -71,7 +68,6 @@ internal ICollection Values() } // bool ContainsKey(K key) - [Pure] internal bool ContainsKey(K key) { if (key == null) @@ -90,7 +86,6 @@ internal void Add(K key, V value) if (ContainsKey(key)) throw new ArgumentException(SR.Argument_AddingDuplicate); - Contract.EndContractBlock(); IMap _this = Unsafe.As>(this); Insert(_this, key, value); @@ -149,7 +144,7 @@ internal bool TryGetValue(K key, out V value) private static V Lookup(IMap _this, K key) { - Contract.Requires(null != key); + Debug.Assert(null != key); try { @@ -165,7 +160,7 @@ private static V Lookup(IMap _this, K key) private static bool Insert(IMap _this, K key, V value) { - Contract.Requires(null != key); + Debug.Assert(null != key); bool replaced = _this.Insert(key, value); return replaced; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs index a006d905d132..16e21e21a15e 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs @@ -9,7 +9,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -34,7 +33,6 @@ private MapViewToReadOnlyCollectionAdapter() } // int Count { get } - [Pure] internal int Count() { object _this = Unsafe.As(this); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs index 8a3e2066cf6a..f083eb29b86f 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs @@ -5,7 +5,6 @@ // using System; -using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs index 71de208c3e75..ff10971f91a8 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs @@ -9,7 +9,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -31,7 +30,6 @@ private VectorToCollectionAdapter() } // int Count { get } - [Pure] internal int Count() { IVector _this = Unsafe.As>(this); @@ -88,7 +86,6 @@ internal void CopyTo(T[] array, int arrayIndex) if (array.Length - arrayIndex < Count()) throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); - Contract.EndContractBlock(); IVector _this = Unsafe.As>(this); int count = Count(); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs index 4d0163e8f990..3e4e5ad67dec 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs @@ -9,7 +9,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs index 9925eea2d032..679060bf4d3a 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs @@ -9,7 +9,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -31,7 +30,6 @@ private VectorViewToReadOnlyCollectionAdapter() } // int Count { get } - [Pure] internal int Count() { IVectorView _this = Unsafe.As>(this); diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs index 1d07a022f470..916ddcc9b6fd 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -32,7 +31,6 @@ public static void AddEventHandler(Func addMethod, throw new ArgumentNullException(nameof(addMethod)); if (removeMethod == null) throw new ArgumentNullException(nameof(removeMethod)); - Contract.EndContractBlock(); // Managed code allows adding a null event handler, the effect is a no-op. To match this behavior // for WinRT events, we simply ignore attempts to add null. @@ -58,7 +56,6 @@ public static void RemoveEventHandler(Action removeMe { if (removeMethod == null) throw new ArgumentNullException(nameof(removeMethod)); - Contract.EndContractBlock(); // Managed code allows removing a null event handler, the effect is a no-op. To match this behavior // for WinRT events, we simply ignore attempts to remove null. @@ -82,7 +79,6 @@ public static void RemoveAllEventHandlers(Action removeM { if (removeMethod == null) throw new ArgumentNullException(nameof(removeMethod)); - Contract.EndContractBlock(); // Delegate to managed event registration implementation or native event registration implementation // They have completely different implementation because native side has its own unique problem to solve - @@ -217,8 +213,8 @@ internal static void AddEventHandler(Func addMetho Action removeMethod, T handler) { - Contract.Requires(addMethod != null); - Contract.Requires(removeMethod != null); + Debug.Assert(addMethod != null); + Debug.Assert(removeMethod != null); // Add the method, and make a note of the token -> delegate mapping. object instance = removeMethod.Target; @@ -248,9 +244,9 @@ internal static void AddEventHandler(Func addMetho // Get the event registration token table for an event. These are indexed by the remove method of the event. private static Dictionary GetEventRegistrationTokenTable(object instance, Action removeMethod) { - Contract.Requires(instance != null); - Contract.Requires(removeMethod != null); - Contract.Requires(s_eventRegistrations != null); + Debug.Assert(instance != null); + Debug.Assert(removeMethod != null); + Debug.Assert(s_eventRegistrations != null); lock (s_eventRegistrations) { @@ -274,7 +270,7 @@ private static Dictionary GetEventRegistrati internal static void RemoveEventHandler(Action removeMethod, T handler) { - Contract.Requires(removeMethod != null); + Debug.Assert(removeMethod != null); object instance = removeMethod.Target; Dictionary registrationTokens = GetEventRegistrationTokenTable(instance, removeMethod); @@ -315,7 +311,7 @@ internal static void RemoveEventHandler(Action remove internal static void RemoveAllEventHandlers(Action removeMethod) { - Contract.Requires(removeMethod != null); + Debug.Assert(removeMethod != null); object instance = removeMethod.Target; Dictionary registrationTokens = GetEventRegistrationTokenTable(instance, removeMethod); @@ -480,7 +476,7 @@ private void CleanupCache() { // Time to destroy cache for this IUnknown */type instance // because the total token list count has dropped to 0 and we don't have any events subscribed - Contract.Requires(s_eventRegistrations != null); + Debug.Assert(s_eventRegistrations != null); BCLDebug.Log("INTEROP", "[WinRT_Eventing] Removing " + _key + " from cache" + "\n"); s_eventRegistrations.Remove(_key); @@ -634,16 +630,16 @@ internal static void AddEventHandler(Func addMetho private static ConditionalWeakTable GetEventRegistrationTokenTableNoCreate(object instance, Action removeMethod, out TokenListCount tokenListCount) { - Contract.Requires(instance != null); - Contract.Requires(removeMethod != null); + Debug.Assert(instance != null); + Debug.Assert(removeMethod != null); return GetEventRegistrationTokenTableInternal(instance, removeMethod, out tokenListCount, /* createIfNotFound = */ false); } private static ConditionalWeakTable GetOrCreateEventRegistrationTokenTable(object instance, Action removeMethod, out TokenListCount tokenListCount) { - Contract.Requires(instance != null); - Contract.Requires(removeMethod != null); + Debug.Assert(instance != null); + Debug.Assert(removeMethod != null); return GetEventRegistrationTokenTableInternal(instance, removeMethod, out tokenListCount, /* createIfNotFound = */ true); } @@ -651,9 +647,9 @@ private static ConditionalWeakTable // Get the event registration token table for an event. These are indexed by the remove method of the event. private static ConditionalWeakTable GetEventRegistrationTokenTableInternal(object instance, Action removeMethod, out TokenListCount tokenListCount, bool createIfNotFound) { - Contract.Requires(instance != null); - Contract.Requires(removeMethod != null); - Contract.Requires(s_eventRegistrations != null); + Debug.Assert(instance != null); + Debug.Assert(removeMethod != null); + Debug.Assert(s_eventRegistrations != null); EventCacheKey eventCacheKey; eventCacheKey.target = instance; @@ -1045,7 +1041,7 @@ internal static void CallRemoveMethods(Action removeMeth internal static unsafe string HStringToString(IntPtr hstring) { - Contract.Requires(Environment.IsWinRTSupported); + Debug.Assert(Environment.IsWinRTSupported); // There is no difference between a null and empty HSTRING if (hstring == IntPtr.Zero) diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs index 0f28d3b080ab..b218b114b451 100644 --- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs +++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Diagnostics.Contracts; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; diff --git a/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs b/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs index a7bf871a3919..0481581c1861 100644 --- a/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs +++ b/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs @@ -5,7 +5,6 @@ using System; using System.Reflection; -using System.Diagnostics.Contracts; using System.IO; using System.Runtime.Versioning; using System.Runtime.CompilerServices; diff --git a/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs b/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs index 4b96836daf50..899bd44d9640 100644 --- a/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs +++ b/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs @@ -22,7 +22,6 @@ using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics; -using System.Diagnostics.Contracts; /* This class allows an application to fail before starting certain @@ -156,7 +155,6 @@ public MemoryFailPoint(int sizeInMegabytes) { if (sizeInMegabytes <= 0) throw new ArgumentOutOfRangeException(nameof(sizeInMegabytes), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); #if !FEATURE_PAL // Remove this when CheckForAvailableMemory is able to provide legitimate estimates ulong size = ((ulong)sizeInMegabytes) << 20; diff --git a/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs b/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs index 52e748db89db..a6e03e70999d 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs @@ -15,7 +15,6 @@ using System; using System.Globalization; -using System.Diagnostics.Contracts; namespace System.Runtime.Serialization { @@ -31,7 +30,6 @@ public Object Convert(Object value, Type type) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); return System.Convert.ChangeType(value, type, CultureInfo.InvariantCulture); } @@ -41,7 +39,6 @@ public Object Convert(Object value, TypeCode typeCode) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); return System.Convert.ChangeType(value, typeCode, CultureInfo.InvariantCulture); } @@ -51,7 +48,6 @@ public bool ToBoolean(Object value) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); return System.Convert.ToBoolean(value, CultureInfo.InvariantCulture); } @@ -61,7 +57,6 @@ public char ToChar(Object value) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); return System.Convert.ToChar(value, CultureInfo.InvariantCulture); } @@ -72,7 +67,6 @@ public sbyte ToSByte(Object value) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); return System.Convert.ToSByte(value, CultureInfo.InvariantCulture); } @@ -82,7 +76,6 @@ public byte ToByte(Object value) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); return System.Convert.ToByte(value, CultureInfo.InvariantCulture); } @@ -92,7 +85,6 @@ public short ToInt16(Object value) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); return System.Convert.ToInt16(value, CultureInfo.InvariantCulture); } @@ -103,7 +95,6 @@ public ushort ToUInt16(Object value) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); return System.Convert.ToUInt16(value, CultureInfo.InvariantCulture); } @@ -113,7 +104,6 @@ public int ToInt32(Object value) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); return System.Convert.ToInt32(value, CultureInfo.InvariantCulture); } @@ -124,7 +114,6 @@ public uint ToUInt32(Object value) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); return System.Convert.ToUInt32(value, CultureInfo.InvariantCulture); } @@ -134,7 +123,6 @@ public long ToInt64(Object value) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); return System.Convert.ToInt64(value, CultureInfo.InvariantCulture); } @@ -145,7 +133,6 @@ public ulong ToUInt64(Object value) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); return System.Convert.ToUInt64(value, CultureInfo.InvariantCulture); } @@ -155,7 +142,6 @@ public float ToSingle(Object value) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); return System.Convert.ToSingle(value, CultureInfo.InvariantCulture); } @@ -165,7 +151,6 @@ public double ToDouble(Object value) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); return System.Convert.ToDouble(value, CultureInfo.InvariantCulture); } @@ -175,7 +160,6 @@ public Decimal ToDecimal(Object value) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); return System.Convert.ToDecimal(value, CultureInfo.InvariantCulture); } @@ -185,7 +169,6 @@ public DateTime ToDateTime(Object value) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); return System.Convert.ToDateTime(value, CultureInfo.InvariantCulture); } @@ -195,7 +178,6 @@ public String ToString(Object value) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); return System.Convert.ToString(value, CultureInfo.InvariantCulture); } } diff --git a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs index b49b372b4bb9..1377350b80c5 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs @@ -24,7 +24,6 @@ using System.Text; using System.Globalization; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Runtime.Serialization { @@ -45,7 +44,6 @@ public static Object GetUninitializedObject(Type type) { throw new ArgumentNullException(nameof(type)); } - Contract.EndContractBlock(); if (!(type is RuntimeType)) { diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs index 8fb54c79a704..694a38214897 100644 --- a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs +++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs @@ -17,7 +17,6 @@ using System.Reflection; using System.Globalization; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Security; using System.Runtime.CompilerServices; @@ -63,7 +62,6 @@ public SerializationInfo(Type type, IFormatterConverter converter, bool requireS throw new ArgumentNullException(nameof(converter)); } - Contract.EndContractBlock(); objectType = type; m_fullTypeName = type.FullName; @@ -92,7 +90,6 @@ public String FullTypeName { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); m_fullTypeName = value; isFullTypeNameSetExplicit = true; @@ -111,7 +108,6 @@ public String AssemblyName { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); if (requireSameTokenInPartialTrust) { DemandForUnsafeAssemblyNameAssignments(m_assemName, value); @@ -127,7 +123,6 @@ public void SetType(Type type) { throw new ArgumentNullException(nameof(type)); } - Contract.EndContractBlock(); if (requireSameTokenInPartialTrust) { @@ -233,7 +228,6 @@ public void AddValue(String name, Object value, Type type) { throw new ArgumentNullException(nameof(type)); } - Contract.EndContractBlock(); AddValueInternal(name, value, type); } @@ -389,7 +383,6 @@ private int FindElement(String name) { throw new ArgumentNullException(nameof(name)); } - Contract.EndContractBlock(); BCLDebug.Trace("SER", "[SerializationInfo.FindElement]Looking for ", name, " CurrMember is: ", m_currMember); int index; if (m_nameToIndex.TryGetValue(name, out index)) @@ -453,7 +446,6 @@ public Object GetValue(String name, Type type) { throw new ArgumentNullException(nameof(type)); } - Contract.EndContractBlock(); RuntimeType rt = type as RuntimeType; if (rt == null) diff --git a/src/mscorlib/src/System/RuntimeHandles.cs b/src/mscorlib/src/System/RuntimeHandles.cs index 20783ef46778..428155ad6039 100644 --- a/src/mscorlib/src/System/RuntimeHandles.cs +++ b/src/mscorlib/src/System/RuntimeHandles.cs @@ -20,7 +20,6 @@ namespace System using System.Globalization; using System.Security; using Microsoft.Win32.SafeHandles; - using System.Diagnostics.Contracts; using StackCrawlMark = System.Threading.StackCrawlMark; public unsafe struct RuntimeTypeHandle : ISerializable @@ -476,7 +475,6 @@ internal static RuntimeType GetTypeByNameUsingCARules(string name, RuntimeModule { if (name == null || name.Length == 0) throw new ArgumentException(null, nameof(name)); - Contract.EndContractBlock(); RuntimeType type = null; GetTypeByNameUsingCARules(name, scope.GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type)); @@ -806,7 +804,6 @@ public bool Equals(RuntimeMethodHandle handle) return handle.Value == Value; } - [Pure] internal bool IsNullHandle() { return m_value == null; @@ -838,7 +835,6 @@ internal static IRuntimeMethodInfo GetCurrentMethod(ref StackCrawlMark stackMark return _GetCurrentMethod(ref stackMark); } - [Pure] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern MethodAttributes GetAttributes(RuntimeMethodHandleInternal method); @@ -878,7 +874,7 @@ internal static RuntimeType GetDeclaringType(IRuntimeMethodInfo method) internal static int GetSlot(IRuntimeMethodInfo method) { - Contract.Requires(method != null); + Debug.Assert(method != null); int slot = RuntimeMethodHandle.GetSlot(method.Value); GC.KeepAlive(method); diff --git a/src/mscorlib/src/System/SharedStatics.cs b/src/mscorlib/src/System/SharedStatics.cs index 5c37f25446ba..dd9c63b33459 100644 --- a/src/mscorlib/src/System/SharedStatics.cs +++ b/src/mscorlib/src/System/SharedStatics.cs @@ -16,7 +16,6 @@ using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System { diff --git a/src/mscorlib/src/System/String.Comparison.cs b/src/mscorlib/src/System/String.Comparison.cs index 6c6c5856bec0..bcb0ee058a3e 100644 --- a/src/mscorlib/src/System/String.Comparison.cs +++ b/src/mscorlib/src/System/String.Comparison.cs @@ -4,7 +4,6 @@ using System.Collections; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; @@ -20,9 +19,8 @@ public partial class String private unsafe static int CompareOrdinalIgnoreCaseHelper(String strA, String strB) { - Contract.Requires(strA != null); - Contract.Requires(strB != null); - Contract.EndContractBlock(); + Debug.Assert(strA != null); + Debug.Assert(strB != null); int length = Math.Min(strA.Length, strB.Length); fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar) @@ -76,9 +74,9 @@ private unsafe static int CompareOrdinalIgnoreCaseHelper(String strA, String str private unsafe static bool EqualsHelper(String strA, String strB) { - Contract.Requires(strA != null); - Contract.Requires(strB != null); - Contract.Requires(strA.Length == strB.Length); + Debug.Assert(strA != null); + Debug.Assert(strB != null); + Debug.Assert(strA.Length == strB.Length); int length = strA.Length; @@ -133,10 +131,9 @@ private unsafe static bool EqualsHelper(String strA, String strB) private unsafe static bool EqualsIgnoreCaseAsciiHelper(String strA, String strB) { - Contract.Requires(strA != null); - Contract.Requires(strB != null); - Contract.Requires(strA.Length == strB.Length); - Contract.EndContractBlock(); + Debug.Assert(strA != null); + Debug.Assert(strB != null); + Debug.Assert(strA.Length == strB.Length); int length = strA.Length; fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar) @@ -172,9 +169,9 @@ private unsafe static bool EqualsIgnoreCaseAsciiHelper(String strA, String strB) private unsafe static bool StartsWithOrdinalHelper(String str, String startsWith) { - Contract.Requires(str != null); - Contract.Requires(startsWith != null); - Contract.Requires(str.Length >= startsWith.Length); + Debug.Assert(str != null); + Debug.Assert(startsWith != null); + Debug.Assert(str.Length >= startsWith.Length); int length = startsWith.Length; @@ -224,8 +221,8 @@ private unsafe static bool StartsWithOrdinalHelper(String str, String startsWith private unsafe static int CompareOrdinalHelper(String strA, String strB) { - Contract.Requires(strA != null); - Contract.Requires(strB != null); + Debug.Assert(strA != null); + Debug.Assert(strB != null); // NOTE: This may be subject to change if eliminating the check // in the callers makes them small enough to be inlined by the JIT @@ -346,7 +343,6 @@ private unsafe static int CompareOrdinalHelper(String strA, String strB) // to determine whether it is lexicographically less, equal, or greater, and then returns // either a negative integer, 0, or a positive integer; respectively. // - [Pure] public static int Compare(String strA, String strB) { return Compare(strA, strB, StringComparison.CurrentCulture); @@ -358,7 +354,6 @@ public static int Compare(String strA, String strB) // negative integer, 0, or a positive integer is returned; respectively. // The case-sensitive option is set by ignoreCase // - [Pure] public static int Compare(String strA, String strB, bool ignoreCase) { var comparisonType = ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture; @@ -368,7 +363,6 @@ public static int Compare(String strA, String strB, bool ignoreCase) // Provides a more flexible function for string comparision. See StringComparison // for meaning of different comparisonType. - [Pure] public static int Compare(String strA, String strB, StringComparison comparisonType) { // Single comparison to check if comparisonType is within [CurrentCulture .. OrdinalIgnoreCase] @@ -376,7 +370,6 @@ public static int Compare(String strA, String strB, StringComparison comparisonT { throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } - Contract.EndContractBlock(); if (object.ReferenceEquals(strA, strB)) { @@ -436,14 +429,12 @@ public static int Compare(String strA, String strB, StringComparison comparisonT // to determine whether it is lexicographically less, equal, or greater, and then a // negative integer, 0, or a positive integer is returned; respectively. // - [Pure] public static int Compare(String strA, String strB, CultureInfo culture, CompareOptions options) { if (culture == null) { throw new ArgumentNullException(nameof(culture)); } - Contract.EndContractBlock(); return culture.CompareInfo.Compare(strA, strB, options); } @@ -456,7 +447,6 @@ public static int Compare(String strA, String strB, CultureInfo culture, Compare // The case-sensitive option is set by ignoreCase, and the culture is set // by culture // - [Pure] public static int Compare(String strA, String strB, bool ignoreCase, CultureInfo culture) { var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None; @@ -467,7 +457,6 @@ public static int Compare(String strA, String strB, bool ignoreCase, CultureInfo // at indexA of length count is compared with the substring of strB // beginning at indexB of the same length. // - [Pure] public static int Compare(String strA, int indexA, String strB, int indexB, int length) { // NOTE: It's important we call the boolean overload, and not the StringComparison @@ -479,7 +468,6 @@ public static int Compare(String strA, int indexA, String strB, int indexB, int // at indexA of length count is compared with the substring of strB // beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean. // - [Pure] public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase) { // Ideally we would just forward to the string.Compare overload that takes @@ -518,7 +506,6 @@ public static int Compare(String strA, int indexA, String strB, int indexB, int // beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean, // and the culture is set by culture. // - [Pure] public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase, CultureInfo culture) { var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None; @@ -530,14 +517,12 @@ public static int Compare(String strA, int indexA, String strB, int indexB, int // at indexA of length length is compared with the substring of strB // beginning at indexB of the same length. // - [Pure] public static int Compare(String strA, int indexA, String strB, int indexB, int length, CultureInfo culture, CompareOptions options) { if (culture == null) { throw new ArgumentNullException(nameof(culture)); } - Contract.EndContractBlock(); int lengthA = length; int lengthB = length; @@ -555,14 +540,12 @@ public static int Compare(String strA, int indexA, String strB, int indexB, int return culture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options); } - [Pure] public static int Compare(String strA, int indexA, String strB, int indexB, int length, StringComparison comparisonType) { if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) { throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } - Contract.EndContractBlock(); if (strA == null || strB == null) { @@ -627,7 +610,6 @@ public static int Compare(String strA, int indexA, String strB, int indexB, int // Compares strA and strB using an ordinal (code-point) comparison. // - [Pure] public static int CompareOrdinal(String strA, String strB) { if (object.ReferenceEquals(strA, strB)) @@ -658,7 +640,6 @@ public static int CompareOrdinal(String strA, String strB) // Compares strA and strB using an ordinal (code-point) comparison. // - [Pure] public static int CompareOrdinal(String strA, int indexA, String strB, int indexB, int length) { if (strA == null || strB == null) @@ -707,7 +688,6 @@ public static int CompareOrdinal(String strA, int indexA, String strB, int index // indicates the relationship. This method returns a value less than 0 if this is less than value, 0 // if this is equal to value, or a value greater than 0 if this is greater than value. // - [Pure] public int CompareTo(Object value) { if (value == null) @@ -727,7 +707,6 @@ public int CompareTo(Object value) // Determines the sorting relation of StrB to the current instance. // - [Pure] public int CompareTo(String strB) { return string.Compare(this, strB, StringComparison.CurrentCulture); @@ -738,13 +717,11 @@ public int CompareTo(String strB) // The case-sensitive and culture-sensitive option is set by options, // and the default culture is used. // - [Pure] public Boolean EndsWith(String value) { return EndsWith(value, StringComparison.CurrentCulture); } - [Pure] public Boolean EndsWith(String value, StringComparison comparisonType) { if ((Object)value == null) @@ -756,7 +733,6 @@ public Boolean EndsWith(String value, StringComparison comparisonType) { throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } - Contract.EndContractBlock(); if ((Object)this == (Object)value) { @@ -792,14 +768,12 @@ public Boolean EndsWith(String value, StringComparison comparisonType) } } - [Pure] public Boolean EndsWith(String value, Boolean ignoreCase, CultureInfo culture) { if (null == value) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); if ((object)this == (object)value) { @@ -815,7 +789,6 @@ public Boolean EndsWith(String value, Boolean ignoreCase, CultureInfo culture) return referenceCulture.CompareInfo.IsSuffix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); } - [Pure] public bool EndsWith(char value) { int thisLen = Length; @@ -839,7 +812,6 @@ public override bool Equals(Object obj) } // Determines whether two strings match. - [Pure] public bool Equals(String value) { if (object.ReferenceEquals(this, value)) @@ -858,12 +830,10 @@ public bool Equals(String value) return EqualsHelper(this, value); } - [Pure] public bool Equals(String value, StringComparison comparisonType) { if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); - Contract.EndContractBlock(); if ((Object)this == (Object)value) { @@ -913,7 +883,6 @@ public bool Equals(String value, StringComparison comparisonType) // Determines whether two Strings match. - [Pure] public static bool Equals(String a, String b) { if ((Object)a == (Object)b) @@ -929,12 +898,10 @@ public static bool Equals(String a, String b) return EqualsHelper(a, b); } - [Pure] public static bool Equals(String a, String b, StringComparison comparisonType) { if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); - Contract.EndContractBlock(); if ((Object)a == (Object)b) { @@ -1070,18 +1037,15 @@ internal int GetLegacyNonRandomizedHashCode() // Determines whether a specified string is a prefix of the current instance // - [Pure] public Boolean StartsWith(String value) { if ((Object)value == null) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); return StartsWith(value, StringComparison.CurrentCulture); } - [Pure] public Boolean StartsWith(String value, StringComparison comparisonType) { if ((Object)value == null) @@ -1093,7 +1057,6 @@ public Boolean StartsWith(String value, StringComparison comparisonType) { throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } - Contract.EndContractBlock(); if ((Object)this == (Object)value) { @@ -1141,14 +1104,12 @@ public Boolean StartsWith(String value, StringComparison comparisonType) } } - [Pure] public Boolean StartsWith(String value, Boolean ignoreCase, CultureInfo culture) { if (null == value) { throw new ArgumentNullException(nameof(value)); } - Contract.EndContractBlock(); if ((object)this == (object)value) { @@ -1164,7 +1125,6 @@ public Boolean StartsWith(String value, Boolean ignoreCase, CultureInfo culture) return referenceCulture.CompareInfo.IsPrefix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); } - [Pure] public bool StartsWith(char value) => Length != 0 && _firstChar == value; } } diff --git a/src/mscorlib/src/System/String.Manipulation.cs b/src/mscorlib/src/System/String.Manipulation.cs index ba78a94b6391..9cb4204159c0 100644 --- a/src/mscorlib/src/System/String.Manipulation.cs +++ b/src/mscorlib/src/System/String.Manipulation.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -16,13 +15,12 @@ public partial class String { unsafe private static void FillStringChecked(String dest, int destPos, String src) { - Contract.Requires(dest != null); - Contract.Requires(src != null); + Debug.Assert(dest != null); + Debug.Assert(src != null); if (src.Length > dest.Length - destPos) { throw new IndexOutOfRangeException(); } - Contract.EndContractBlock(); fixed (char* pDest = &dest._firstChar) fixed (char* pSrc = &src._firstChar) @@ -33,9 +31,6 @@ unsafe private static void FillStringChecked(String dest, int destPos, String sr public static String Concat(Object arg0) { - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); - if (arg0 == null) { return String.Empty; @@ -45,9 +40,6 @@ public static String Concat(Object arg0) public static String Concat(Object arg0, Object arg1) { - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); - if (arg0 == null) { arg0 = String.Empty; @@ -62,9 +54,6 @@ public static String Concat(Object arg0, Object arg1) public static String Concat(Object arg0, Object arg1, Object arg2) { - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); - if (arg0 == null) { arg0 = String.Empty; @@ -89,8 +78,6 @@ public static string Concat(params object[] args) { throw new ArgumentNullException(nameof(args)); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); if (args.Length <= 1) { @@ -154,8 +141,6 @@ public static string Concat(IEnumerable values) { if (values == null) throw new ArgumentNullException(nameof(values)); - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); using (IEnumerator en = values.GetEnumerator()) { @@ -204,8 +189,6 @@ public static string Concat(IEnumerable values) { if (values == null) throw new ArgumentNullException(nameof(values)); - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); using (IEnumerator en = values.GetEnumerator()) { @@ -235,12 +218,6 @@ public static string Concat(IEnumerable values) public static String Concat(String str0, String str1) { - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(Contract.Result().Length == - (str0 == null ? 0 : str0.Length) + - (str1 == null ? 0 : str1.Length)); - Contract.EndContractBlock(); - if (IsNullOrEmpty(str0)) { if (IsNullOrEmpty(str1)) @@ -267,13 +244,6 @@ public static String Concat(String str0, String str1) public static String Concat(String str0, String str1, String str2) { - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(Contract.Result().Length == - (str0 == null ? 0 : str0.Length) + - (str1 == null ? 0 : str1.Length) + - (str2 == null ? 0 : str2.Length)); - Contract.EndContractBlock(); - if (IsNullOrEmpty(str0)) { return Concat(str1, str2); @@ -301,14 +271,6 @@ public static String Concat(String str0, String str1, String str2) public static String Concat(String str0, String str1, String str2, String str3) { - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(Contract.Result().Length == - (str0 == null ? 0 : str0.Length) + - (str1 == null ? 0 : str1.Length) + - (str2 == null ? 0 : str2.Length) + - (str3 == null ? 0 : str3.Length)); - Contract.EndContractBlock(); - if (IsNullOrEmpty(str0)) { return Concat(str1, str2, str3); @@ -344,8 +306,6 @@ public static String Concat(params String[] values) { if (values == null) throw new ArgumentNullException(nameof(values)); - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); if (values.Length <= 1) { @@ -412,19 +372,16 @@ public static String Concat(params String[] values) public static String Format(String format, Object arg0) { - Contract.Ensures(Contract.Result() != null); return FormatHelper(null, format, new ParamsArray(arg0)); } public static String Format(String format, Object arg0, Object arg1) { - Contract.Ensures(Contract.Result() != null); return FormatHelper(null, format, new ParamsArray(arg0, arg1)); } public static String Format(String format, Object arg0, Object arg1, Object arg2) { - Contract.Ensures(Contract.Result() != null); return FormatHelper(null, format, new ParamsArray(arg0, arg1, arg2)); } @@ -436,27 +393,22 @@ public static String Format(String format, params Object[] args) // args and format are null. The actual null check for format is in FormatHelper. throw new ArgumentNullException((format == null) ? nameof(format) : nameof(args)); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return FormatHelper(null, format, new ParamsArray(args)); } public static String Format(IFormatProvider provider, String format, Object arg0) { - Contract.Ensures(Contract.Result() != null); return FormatHelper(provider, format, new ParamsArray(arg0)); } public static String Format(IFormatProvider provider, String format, Object arg0, Object arg1) { - Contract.Ensures(Contract.Result() != null); return FormatHelper(provider, format, new ParamsArray(arg0, arg1)); } public static String Format(IFormatProvider provider, String format, Object arg0, Object arg1, Object arg2) { - Contract.Ensures(Contract.Result() != null); return FormatHelper(provider, format, new ParamsArray(arg0, arg1, arg2)); } @@ -468,8 +420,6 @@ public static String Format(IFormatProvider provider, String format, params Obje // args and format are null. The actual null check for format is in FormatHelper. throw new ArgumentNullException((format == null) ? nameof(format) : nameof(args)); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return FormatHelper(provider, format, new ParamsArray(args)); } @@ -491,9 +441,6 @@ public String Insert(int startIndex, String value) throw new ArgumentNullException(nameof(value)); if (startIndex < 0 || startIndex > this.Length) throw new ArgumentOutOfRangeException(nameof(startIndex)); - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(Contract.Result().Length == this.Length + value.Length); - Contract.EndContractBlock(); int oldLength = Length; int insertLength = value.Length; @@ -830,13 +777,11 @@ private unsafe static string JoinCore(char* separator, int separatorLength, stri // // - [Pure] public String PadLeft(int totalWidth) { return PadLeft(totalWidth, ' '); } - [Pure] public String PadLeft(int totalWidth, char paddingChar) { if (totalWidth < 0) @@ -861,13 +806,11 @@ public String PadLeft(int totalWidth, char paddingChar) return result; } - [Pure] public String PadRight(int totalWidth) { return PadRight(totalWidth, ' '); } - [Pure] public String PadRight(int totalWidth, char paddingChar) { if (totalWidth < 0) @@ -903,9 +846,6 @@ public String Remove(int startIndex, int count) if (count > Length - startIndex) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_IndexCount); - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(Contract.Result().Length == this.Length - count); - Contract.EndContractBlock(); if (count == 0) return this; @@ -943,25 +883,17 @@ public string Remove(int startIndex) SR.ArgumentOutOfRange_StartIndexLessThanLength); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return Substring(0, startIndex); } public string Replace(string oldValue, string newValue, bool ignoreCase, CultureInfo culture) { - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); - return ReplaceCore(oldValue, newValue, culture, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); } public string Replace(string oldValue, string newValue, StringComparison comparisonType) { - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); - switch (comparisonType) { case StringComparison.CurrentCulture: @@ -1044,10 +976,6 @@ private unsafe String ReplaceCore(string oldValue, string newValue, CultureInfo // public String Replace(char oldChar, char newChar) { - Contract.Ensures(Contract.Result() != null); - Contract.Ensures(Contract.Result().Length == this.Length); - Contract.EndContractBlock(); - if (oldChar == newChar) return this; @@ -1120,21 +1048,17 @@ public String Replace(String oldValue, String newValue) if (oldValue == null) throw new ArgumentNullException(nameof(oldValue)); // Note that if newValue is null, we treat it like String.Empty. - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return ReplaceInternal(oldValue, newValue); } public unsafe String[] Split(char separator, StringSplitOptions options = StringSplitOptions.None) { - Contract.Ensures(Contract.Result() != null); return SplitInternal(&separator, 1, int.MaxValue, options); } public unsafe String[] Split(char separator, int count, StringSplitOptions options = StringSplitOptions.None) { - Contract.Ensures(Contract.Result() != null); return SplitInternal(&separator, 1, count, options); } @@ -1149,7 +1073,6 @@ public unsafe String[] Split(char separator, int count, StringSplitOptions optio // public String[] Split(params char[] separator) { - Contract.Ensures(Contract.Result() != null); return SplitInternal(separator, Int32.MaxValue, StringSplitOptions.None); } @@ -1166,19 +1089,16 @@ public String[] Split(params char[] separator) // public string[] Split(char[] separator, int count) { - Contract.Ensures(Contract.Result() != null); return SplitInternal(separator, count, StringSplitOptions.None); } public String[] Split(char[] separator, StringSplitOptions options) { - Contract.Ensures(Contract.Result() != null); return SplitInternal(separator, Int32.MaxValue, options); } public String[] Split(char[] separator, int count, StringSplitOptions options) { - Contract.Ensures(Contract.Result() != null); return SplitInternal(separator, count, options); } @@ -1199,8 +1119,6 @@ private unsafe String[] SplitInternal(char* separators, int separatorsLength, in if (options < StringSplitOptions.None || options > StringSplitOptions.RemoveEmptyEntries) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, options)); - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); bool omitEmptyEntries = (options == StringSplitOptions.RemoveEmptyEntries); @@ -1235,25 +1153,21 @@ private unsafe String[] SplitInternal(char* separators, int separatorsLength, in public String[] Split(String separator, StringSplitOptions options = StringSplitOptions.None) { - Contract.Ensures(Contract.Result() != null); return SplitInternal(separator ?? String.Empty, null, Int32.MaxValue, options); } public String[] Split(String separator, Int32 count, StringSplitOptions options = StringSplitOptions.None) { - Contract.Ensures(Contract.Result() != null); return SplitInternal(separator ?? String.Empty, null, count, options); } public String[] Split(String[] separator, StringSplitOptions options) { - Contract.Ensures(Contract.Result() != null); return SplitInternal(null, separator, Int32.MaxValue, options); } public String[] Split(String[] separator, Int32 count, StringSplitOptions options) { - Contract.Ensures(Contract.Result() != null); return SplitInternal(null, separator, count, options); } @@ -1269,7 +1183,6 @@ private String[] SplitInternal(String separator, String[] separators, Int32 coun { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)options)); } - Contract.EndContractBlock(); bool omitEmptyEntries = (options == StringSplitOptions.RemoveEmptyEntries); @@ -1331,9 +1244,8 @@ private String[] SplitInternal(String separator, String[] separators, Int32 coun private String[] SplitKeepEmptyEntries(Int32[] sepList, Int32[] lengthList, Int32 defaultLength, Int32 numReplaces, int count) { - Contract.Requires(numReplaces >= 0); - Contract.Requires(count >= 2); - Contract.Ensures(Contract.Result() != null); + Debug.Assert(numReplaces >= 0); + Debug.Assert(count >= 2); int currIndex = 0; int arrIndex = 0; @@ -1370,9 +1282,8 @@ private String[] SplitKeepEmptyEntries(Int32[] sepList, Int32[] lengthList, Int3 // This function will not keep the Empty String private String[] SplitOmitEmptyEntries(Int32[] sepList, Int32[] lengthList, Int32 defaultLength, Int32 numReplaces, int count) { - Contract.Requires(numReplaces >= 0); - Contract.Requires(count >= 2); - Contract.Ensures(Contract.Result() != null); + Debug.Assert(numReplaces >= 0); + Debug.Assert(count >= 2); // Allocate array to hold items. This array may not be // filled completely in this function, we will create a @@ -1580,7 +1491,6 @@ public String Substring(int startIndex, int length) { throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexLength); } - Contract.EndContractBlock(); if (length == 0) { @@ -1612,78 +1522,56 @@ private unsafe string InternalSubString(int startIndex, int length) } // Creates a copy of this string in lower case. - [Pure] public String ToLower() { - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return this.ToLower(CultureInfo.CurrentCulture); } // Creates a copy of this string in lower case. The culture is set by culture. - [Pure] public String ToLower(CultureInfo culture) { if (culture == null) { throw new ArgumentNullException(nameof(culture)); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return culture.TextInfo.ToLower(this); } // Creates a copy of this string in lower case based on invariant culture. - [Pure] public String ToLowerInvariant() { - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return this.ToLower(CultureInfo.InvariantCulture); } // Creates a copy of this string in upper case. - [Pure] public String ToUpper() { - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return this.ToUpper(CultureInfo.CurrentCulture); } // Creates a copy of this string in upper case. The culture is set by culture. - [Pure] public String ToUpper(CultureInfo culture) { if (culture == null) { throw new ArgumentNullException(nameof(culture)); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return culture.TextInfo.ToUpper(this); } //Creates a copy of this string in upper case based on invariant culture. - [Pure] public String ToUpperInvariant() { - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return this.ToUpper(CultureInfo.InvariantCulture); } // Trims the whitespace from both ends of the string. Whitespace is defined by // Char.IsWhiteSpace. // - [Pure] public string Trim() { - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); - return TrimWhiteSpaceHelper(TrimType.Both); } @@ -1691,7 +1579,6 @@ public string Trim() public unsafe string Trim(char trimChar) => TrimHelper(&trimChar, 1, TrimType.Both); // Removes a set of characters from the beginning and end of this string. - [Pure] public unsafe string Trim(params char[] trimChars) { if (trimChars == null || trimChars.Length == 0) diff --git a/src/mscorlib/src/System/String.Searching.cs b/src/mscorlib/src/System/String.Searching.cs index 02e800427b5b..0be214d0d91d 100644 --- a/src/mscorlib/src/System/String.Searching.cs +++ b/src/mscorlib/src/System/String.Searching.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; @@ -10,13 +9,11 @@ namespace System { public partial class String { - [Pure] public bool Contains(string value) { return (IndexOf(value, StringComparison.Ordinal) >= 0); } - [Pure] public bool Contains(string value, StringComparison comparisonType) { return (IndexOf(value, comparisonType) >= 0); @@ -25,19 +22,16 @@ public bool Contains(string value, StringComparison comparisonType) // Returns the index of the first occurrence of a specified character in the current instance. // The search starts at startIndex and runs thorough the next count characters. // - [Pure] public int IndexOf(char value) { return IndexOf(value, 0, this.Length); } - [Pure] public int IndexOf(char value, int startIndex) { return IndexOf(value, startIndex, this.Length - startIndex); } - [Pure] public unsafe int IndexOf(char value, int startIndex, int count) { if (startIndex < 0 || startIndex > Length) @@ -83,19 +77,16 @@ public unsafe int IndexOf(char value, int startIndex, int count) // Returns the index of the first occurrence of any specified character in the current instance. // The search starts at startIndex and runs to startIndex + count -1. // - [Pure] public int IndexOfAny(char[] anyOf) { return IndexOfAny(anyOf, 0, this.Length); } - [Pure] public int IndexOfAny(char[] anyOf, int startIndex) { return IndexOfAny(anyOf, startIndex, this.Length - startIndex); } - [Pure] public int IndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) @@ -194,7 +185,6 @@ private unsafe int IndexOfAny(char value1, char value2, char value3, int startIn // the first character of this string, it is case-sensitive and the current culture // comparison is used. // - [Pure] public int IndexOf(String value) { return IndexOf(value, StringComparison.CurrentCulture); @@ -204,7 +194,6 @@ public int IndexOf(String value) // string, according to the specified search criteria. The search begins at // startIndex, it is case-sensitive and the current culture comparison is used. // - [Pure] public int IndexOf(String value, int startIndex) { return IndexOf(value, startIndex, StringComparison.CurrentCulture); @@ -214,7 +203,6 @@ public int IndexOf(String value, int startIndex) // string, according to the specified search criteria. The search begins at // startIndex, ends at endIndex and the current culture comparison is used. // - [Pure] public int IndexOf(String value, int startIndex, int count) { if (startIndex < 0 || startIndex > this.Length) @@ -226,24 +214,20 @@ public int IndexOf(String value, int startIndex, int count) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); } - Contract.EndContractBlock(); return IndexOf(value, startIndex, count, StringComparison.CurrentCulture); } - [Pure] public int IndexOf(String value, StringComparison comparisonType) { return IndexOf(value, 0, this.Length, comparisonType); } - [Pure] public int IndexOf(String value, int startIndex, StringComparison comparisonType) { return IndexOf(value, startIndex, this.Length - startIndex, comparisonType); } - [Pure] public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType) { // Validate inputs @@ -255,7 +239,6 @@ public int IndexOf(String value, int startIndex, int count, StringComparison com if (count < 0 || startIndex > this.Length - count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); - Contract.EndContractBlock(); switch (comparisonType) { @@ -290,19 +273,16 @@ public int IndexOf(String value, int startIndex, int count, StringComparison com // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // - [Pure] public int LastIndexOf(char value) { return LastIndexOf(value, this.Length - 1, this.Length); } - [Pure] public int LastIndexOf(char value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1); } - [Pure] public unsafe int LastIndexOf(char value, int startIndex, int count) { if (Length == 0) @@ -356,19 +336,16 @@ public unsafe int LastIndexOf(char value, int startIndex, int count) // //ForceInline ... Jit can't recognize String.get_Length to determine that this is "fluff" - [Pure] public int LastIndexOfAny(char[] anyOf) { return LastIndexOfAny(anyOf, this.Length - 1, this.Length); } - [Pure] public int LastIndexOfAny(char[] anyOf, int startIndex) { return LastIndexOfAny(anyOf, startIndex, startIndex + 1); } - [Pure] [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int LastIndexOfAny(char[] anyOf, int startIndex, int count); @@ -378,48 +355,40 @@ public int LastIndexOfAny(char[] anyOf, int startIndex) // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // - [Pure] public int LastIndexOf(String value) { return LastIndexOf(value, this.Length - 1, this.Length, StringComparison.CurrentCulture); } - [Pure] public int LastIndexOf(String value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1, StringComparison.CurrentCulture); } - [Pure] public int LastIndexOf(String value, int startIndex, int count) { if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); } - Contract.EndContractBlock(); return LastIndexOf(value, startIndex, count, StringComparison.CurrentCulture); } - [Pure] public int LastIndexOf(String value, StringComparison comparisonType) { return LastIndexOf(value, this.Length - 1, this.Length, comparisonType); } - [Pure] public int LastIndexOf(String value, int startIndex, StringComparison comparisonType) { return LastIndexOf(value, startIndex, startIndex + 1, comparisonType); } - [Pure] public int LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType) { if (value == null) throw new ArgumentNullException(nameof(value)); - Contract.EndContractBlock(); // Special case for 0 length input strings if (this.Length == 0 && (startIndex == -1 || startIndex == 0)) diff --git a/src/mscorlib/src/System/String.cs b/src/mscorlib/src/System/String.cs index c74abe990361..cd9689978e81 100644 --- a/src/mscorlib/src/System/String.cs +++ b/src/mscorlib/src/System/String.cs @@ -28,7 +28,6 @@ namespace System using System.Runtime.Versioning; using Microsoft.Win32; using System.Diagnostics; - using System.Diagnostics.Contracts; using System.Security; // @@ -72,8 +71,7 @@ public sealed partial class String : IComparable, ICloneable, IConvertible, IEnu // internal unsafe static string SmallCharToUpper(string strIn) { - Contract.Requires(strIn != null); - Contract.EndContractBlock(); + Debug.Assert(strIn != null); // // Get the length and pointers to each of the buffers. Walk the length // of the string and copy the characters from the inBuffer to the outBuffer, @@ -102,7 +100,6 @@ internal unsafe static string SmallCharToUpper(string strIn) // Gets the character at a specified position. // - // Spec#: Apply the precondition here using a contract assembly. Potential perf issue. [System.Runtime.CompilerServices.IndexerName("Chars")] public extern char this[int index] { @@ -127,7 +124,6 @@ unsafe public void CopyTo(int sourceIndex, char[] destination, int destinationIn throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_IndexCount); if (destinationIndex > destination.Length - count || destinationIndex < 0) throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_IndexCount); - Contract.EndContractBlock(); // Note: fixed does not like empty arrays if (count > 0) @@ -164,7 +160,6 @@ unsafe public char[] ToCharArray(int startIndex, int length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); if (length > 0) { @@ -179,13 +174,11 @@ unsafe public char[] ToCharArray(int startIndex, int length) return Array.Empty(); } - [Pure] public static bool IsNullOrEmpty(String value) { return (value == null || value.Length == 0); } - [Pure] public static bool IsNullOrWhiteSpace(String value) { if (value == null) return true; @@ -205,7 +198,6 @@ public static bool IsNullOrWhiteSpace(String value) /// for(int i = 0; i < str.Length; i++) str[i] /// The actually code generated for this will be one instruction and will be inlined. // - // Spec#: Add postcondition in a contract assembly. Potential perf problem. public extern int Length { [MethodImplAttribute(MethodImplOptions.InternalCall)] @@ -265,8 +257,8 @@ unsafe static private String CreateString(sbyte* value, int startIndex, int leng unsafe static internal String CreateStringFromEncoding( byte* bytes, int byteLength, Encoding encoding) { - Contract.Requires(bytes != null); - Contract.Requires(byteLength >= 0); + Debug.Assert(bytes != null); + Debug.Assert(byteLength >= 0); // Get our string length int stringLength = encoding.GetCharCount(bytes, byteLength, null); @@ -437,7 +429,6 @@ private String CtorCharArrayStartLength(char[] value, int startIndex, int length if (startIndex > value.Length - length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); - Contract.EndContractBlock(); if (length > 0) { @@ -637,7 +628,6 @@ private unsafe String CtorCharPtrStartLength(char* ptr, int startIndex, int leng { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); } - Contract.EndContractBlock(); Debug.Assert(this == null, "this == null"); // this is the string constructor, we allocate it char* pFrom = ptr + startIndex; @@ -710,15 +700,11 @@ public static string Create(int length, TState state, SpanAction() != null); - Contract.EndContractBlock(); return this; } public String ToString(IFormatProvider provider) { - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return this; } @@ -726,8 +712,6 @@ public String ToString(IFormatProvider provider) // There's no point in cloning a string since they're immutable, so we simply return this. public Object Clone() { - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); return this; } @@ -737,8 +721,6 @@ unsafe public static String Copy(String str) { throw new ArgumentNullException(nameof(str)); } - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); int length = str.Length; @@ -758,22 +740,16 @@ public static String Intern(String str) { throw new ArgumentNullException(nameof(str)); } - Contract.Ensures(Contract.Result().Length == str.Length); - Contract.Ensures(str.Equals(Contract.Result())); - Contract.EndContractBlock(); return Thread.GetDomain().GetOrInternString(str); } - [Pure] public static String IsInterned(String str) { if (str == null) { throw new ArgumentNullException(nameof(str)); } - Contract.Ensures(Contract.Result() == null || Contract.Result().Length == str.Length); - Contract.EndContractBlock(); return Thread.GetDomain().IsStringInterned(str); } @@ -882,24 +858,18 @@ Object IConvertible.ToType(Type type, IFormatProvider provider) public CharEnumerator GetEnumerator() { - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); BCLDebug.Perf(false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead."); return new CharEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { - Contract.Ensures(Contract.Result>() != null); - Contract.EndContractBlock(); BCLDebug.Perf(false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead."); return new CharEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { - Contract.Ensures(Contract.Result() != null); - Contract.EndContractBlock(); BCLDebug.Perf(false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead."); return new CharEnumerator(this); } diff --git a/src/mscorlib/src/System/StubHelpers.cs b/src/mscorlib/src/System/StubHelpers.cs index e8ddd393f617..ff74d4c3c5a5 100644 --- a/src/mscorlib/src/System/StubHelpers.cs +++ b/src/mscorlib/src/System/StubHelpers.cs @@ -17,7 +17,6 @@ namespace System.StubHelpers using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Diagnostics; - using System.Diagnostics.Contracts; internal static class AnsiCharMarshaler { @@ -1446,8 +1445,6 @@ static internal unsafe int ConvertToNative(Exception ex) static internal unsafe Exception ConvertToManaged(int hr) { - Contract.Ensures(Contract.Result() != null || hr >= 0); - if (!Environment.IsWinRTSupported) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT); diff --git a/src/mscorlib/src/System/Text/Normalization.Windows.cs b/src/mscorlib/src/System/Text/Normalization.Windows.cs index 8e284e798d08..96389bfa1881 100644 --- a/src/mscorlib/src/System/Text/Normalization.Windows.cs +++ b/src/mscorlib/src/System/Text/Normalization.Windows.cs @@ -10,7 +10,6 @@ using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Text { diff --git a/src/mscorlib/src/System/Threading/EventWaitHandle.cs b/src/mscorlib/src/System/Threading/EventWaitHandle.cs index cfb9c2841554..82312e644d33 100644 --- a/src/mscorlib/src/System/Threading/EventWaitHandle.cs +++ b/src/mscorlib/src/System/Threading/EventWaitHandle.cs @@ -34,7 +34,6 @@ namespace System.Threading using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.AccessControl; - using System.Diagnostics.Contracts; [ComVisibleAttribute(true)] public class EventWaitHandle : WaitHandle @@ -57,7 +56,6 @@ public EventWaitHandle(bool initialState, EventResetMode mode, string name) } #endif } - Contract.EndContractBlock(); uint eventFlags = initialState ? Win32Native.CREATE_EVENT_INITIAL_SET : 0; switch (mode) @@ -106,7 +104,6 @@ internal unsafe EventWaitHandle(bool initialState, EventResetMode mode, string n } #endif } - Contract.EndContractBlock(); Win32Native.SECURITY_ATTRIBUTES secAttrs = null; uint eventFlags = initialState ? Win32Native.CREATE_EVENT_INITIAL_SET : 0; @@ -192,7 +189,6 @@ private static OpenExistingResult OpenExistingWorker(string name, EventWaitHandl throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name)); } - Contract.EndContractBlock(); result = null; diff --git a/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs b/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs index 0807e1930190..d2767710ecf1 100644 --- a/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs +++ b/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs @@ -13,7 +13,6 @@ // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Threading { @@ -242,8 +241,6 @@ private void Initialize(bool initialState, int spinCount) /// private void EnsureLockObjectCreated() { - Contract.Ensures(m_lock != null); - if (m_lock != null) return; diff --git a/src/mscorlib/src/System/Threading/Monitor.cs b/src/mscorlib/src/System/Threading/Monitor.cs index 0df64a5e5cb8..dee4118fe1b5 100644 --- a/src/mscorlib/src/System/Threading/Monitor.cs +++ b/src/mscorlib/src/System/Threading/Monitor.cs @@ -22,7 +22,6 @@ using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Threading { @@ -217,7 +216,6 @@ public static void Pulse(Object obj) { throw new ArgumentNullException(nameof(obj)); } - Contract.EndContractBlock(); ObjPulse(obj); } @@ -233,7 +231,6 @@ public static void PulseAll(Object obj) { throw new ArgumentNullException(nameof(obj)); } - Contract.EndContractBlock(); ObjPulseAll(obj); } diff --git a/src/mscorlib/src/System/Threading/Mutex.cs b/src/mscorlib/src/System/Threading/Mutex.cs index 095c27bf8eab..64bfc852343b 100644 --- a/src/mscorlib/src/System/Threading/Mutex.cs +++ b/src/mscorlib/src/System/Threading/Mutex.cs @@ -24,7 +24,6 @@ namespace System.Threading using System.Runtime.Versioning; using System.Security; using System.Diagnostics; - using System.Diagnostics.Contracts; public sealed class Mutex : WaitHandle { @@ -55,7 +54,6 @@ internal unsafe Mutex(bool initiallyOwned, String name, out bool createdNew, Mut throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name)); } #endif // PLATFORM_WINDOWS - Contract.EndContractBlock(); Win32Native.SECURITY_ATTRIBUTES secAttrs = null; CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs); @@ -230,7 +228,6 @@ private static OpenExistingResult OpenExistingWorker(string name, MutexRights ri throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name)); } #endif - Contract.EndContractBlock(); result = null; diff --git a/src/mscorlib/src/System/Threading/Overlapped.cs b/src/mscorlib/src/System/Threading/Overlapped.cs index 0830ee6b6cc8..2a9f1e299904 100644 --- a/src/mscorlib/src/System/Threading/Overlapped.cs +++ b/src/mscorlib/src/System/Threading/Overlapped.cs @@ -31,7 +31,6 @@ using System.Security; using System.Runtime.ConstrainedExecution; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Collections.Concurrent; namespace System.Threading @@ -348,7 +347,6 @@ unsafe public static Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr) { if (nativeOverlappedPtr == null) throw new ArgumentNullException(nameof(nativeOverlappedPtr)); - Contract.EndContractBlock(); Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped; @@ -360,7 +358,6 @@ unsafe public static void Free(NativeOverlapped* nativeOverlappedPtr) { if (nativeOverlappedPtr == null) throw new ArgumentNullException(nameof(nativeOverlappedPtr)); - Contract.EndContractBlock(); Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped; OverlappedData.FreeNativeOverlapped(nativeOverlappedPtr); diff --git a/src/mscorlib/src/System/Threading/Semaphore.cs b/src/mscorlib/src/System/Threading/Semaphore.cs index 136eee6e7655..cec37a51cf2f 100644 --- a/src/mscorlib/src/System/Threading/Semaphore.cs +++ b/src/mscorlib/src/System/Threading/Semaphore.cs @@ -5,7 +5,6 @@ using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.IO; using System.Runtime.InteropServices; using System.Security; diff --git a/src/mscorlib/src/System/Threading/SemaphoreSlim.cs b/src/mscorlib/src/System/Threading/SemaphoreSlim.cs index a61753d9a9c8..9e713cefd7b2 100644 --- a/src/mscorlib/src/System/Threading/SemaphoreSlim.cs +++ b/src/mscorlib/src/System/Threading/SemaphoreSlim.cs @@ -17,7 +17,6 @@ using System.Diagnostics; using System.Security; using System.Runtime.InteropServices; -using System.Diagnostics.Contracts; using System.Threading.Tasks; // The class will be part of the current System.Threading namespace @@ -709,7 +708,7 @@ private TaskNode CreateAndAddAsyncWaiter() /// true if the waiter was in the list; otherwise, false. private bool RemoveAsyncWaiter(TaskNode task) { - Contract.Requires(task != null, "Expected non-null task"); + Debug.Assert(task != null, "Expected non-null task"); Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held"); // Is the task in the list? To be in the list, either it's the head or it has a predecessor that's in the list. diff --git a/src/mscorlib/src/System/Threading/SynchronizationContext.cs b/src/mscorlib/src/System/Threading/SynchronizationContext.cs index 676a198ee79f..be4bff7dd501 100644 --- a/src/mscorlib/src/System/Threading/SynchronizationContext.cs +++ b/src/mscorlib/src/System/Threading/SynchronizationContext.cs @@ -22,7 +22,6 @@ namespace System.Threading using System.Reflection; using System.Security; using System.Diagnostics; - using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; @@ -143,7 +142,6 @@ protected static int WaitHelper(IntPtr[] waitHandles, bool waitAll, int millisec { throw new ArgumentNullException(nameof(waitHandles)); } - Contract.EndContractBlock(); return WaitHelperNative(waitHandles, waitAll, millisecondsTimeout); } diff --git a/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs b/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs index ec154f9efb2d..2b14f375d3dd 100644 --- a/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs +++ b/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs @@ -8,7 +8,6 @@ using System; using System.Security; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs b/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs index 765dcd840810..7d60e4ca1602 100644 --- a/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs +++ b/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs @@ -18,7 +18,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.Contracts; using System.Security; namespace System.Threading.Tasks @@ -105,7 +104,6 @@ public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConc if (taskScheduler == null) throw new ArgumentNullException(nameof(taskScheduler)); if (maxConcurrencyLevel == 0 || maxConcurrencyLevel < -1) throw new ArgumentOutOfRangeException(nameof(maxConcurrencyLevel)); if (maxItemsPerTask == 0 || maxItemsPerTask < -1) throw new ArgumentOutOfRangeException(nameof(maxItemsPerTask)); - Contract.EndContractBlock(); // Store configuration m_underlyingTaskScheduler = taskScheduler; @@ -202,7 +200,7 @@ private bool ReadyToComplete /// Completes the completion task asynchronously. private void CompleteTaskAsync() { - Contract.Requires(ReadyToComplete, "The block must be ready to complete to be here."); + Debug.Assert(ReadyToComplete, "The block must be ready to complete to be here."); ContractAssertMonitorStatus(ValueLock, held: true); // Ensure we only try to complete once, then schedule completion @@ -229,7 +227,7 @@ private void CompleteTaskAsync() /// The faulted worker task that's initiating the shutdown. private void FaultWithTask(Task faultedTask) { - Contract.Requires(faultedTask != null && faultedTask.IsFaulted && faultedTask.Exception.InnerExceptions.Count > 0, + Debug.Assert(faultedTask != null && faultedTask.IsFaulted && faultedTask.Exception.InnerExceptions.Count > 0, "Needs a task in the faulted state and thus with exceptions."); ContractAssertMonitorStatus(ValueLock, held: true); @@ -346,8 +344,8 @@ private void ProcessAsyncIfNecessary(bool fairly = false) /// private void ProcessExclusiveTasks() { - Contract.Requires(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "Processing exclusive tasks requires being in exclusive mode."); - Contract.Requires(!m_exclusiveTaskScheduler.m_tasks.IsEmpty, "Processing exclusive tasks requires tasks to be processed."); + Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "Processing exclusive tasks requires being in exclusive mode."); + Debug.Assert(!m_exclusiveTaskScheduler.m_tasks.IsEmpty, "Processing exclusive tasks requires tasks to be processed."); ContractAssertMonitorStatus(ValueLock, held: false); try { @@ -396,7 +394,7 @@ private void ProcessExclusiveTasks() /// private void ProcessConcurrentTasks() { - Contract.Requires(m_processingCount > 0, "Processing concurrent tasks requires us to be in concurrent mode."); + Debug.Assert(m_processingCount > 0, "Processing concurrent tasks requires us to be in concurrent mode."); ContractAssertMonitorStatus(ValueLock, held: false); try { @@ -504,10 +502,10 @@ private sealed class ConcurrentExclusiveTaskScheduler : TaskScheduler /// The processing mode of this scheduler. internal ConcurrentExclusiveTaskScheduler(ConcurrentExclusiveSchedulerPair pair, int maxConcurrencyLevel, ProcessingMode processingMode) { - Contract.Requires(pair != null, "Scheduler must be associated with a valid pair."); - Contract.Requires(processingMode == ProcessingMode.ProcessingConcurrentTasks || processingMode == ProcessingMode.ProcessingExclusiveTask, + Debug.Assert(pair != null, "Scheduler must be associated with a valid pair."); + Debug.Assert(processingMode == ProcessingMode.ProcessingConcurrentTasks || processingMode == ProcessingMode.ProcessingExclusiveTask, "Scheduler must be for concurrent or exclusive processing."); - Contract.Requires( + Debug.Assert( (processingMode == ProcessingMode.ProcessingConcurrentTasks && (maxConcurrencyLevel >= 1 || maxConcurrencyLevel == UNLIMITED_PROCESSING)) || (processingMode == ProcessingMode.ProcessingExclusiveTask && maxConcurrencyLevel == 1), "If we're in concurrent mode, our concurrency level should be positive or unlimited. If exclusive, it should be 1."); @@ -664,7 +662,7 @@ private sealed class DebugView /// The scheduler being debugged. public DebugView(ConcurrentExclusiveTaskScheduler scheduler) { - Contract.Requires(scheduler != null, "Need a scheduler with which to construct the debug view."); + Debug.Assert(scheduler != null, "Need a scheduler with which to construct the debug view."); m_taskScheduler = scheduler; } @@ -687,7 +685,7 @@ private sealed class DebugView /// The pair being debugged. public DebugView(ConcurrentExclusiveSchedulerPair pair) { - Contract.Requires(pair != null, "Need a pair with which to construct the debug view."); + Debug.Assert(pair != null, "Need a pair with which to construct the debug view."); m_pair = pair; } @@ -730,7 +728,7 @@ private ProcessingMode ModeForDebugger [Conditional("DEBUG")] internal static void ContractAssertMonitorStatus(object syncObj, bool held) { - Contract.Requires(syncObj != null, "The monitor object to check must be provided."); + Debug.Assert(syncObj != null, "The monitor object to check must be provided."); #if PRENET45 #if DEBUG // This check is expensive, diff --git a/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs b/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs index bf63a53df96a..4615d43826cd 100644 --- a/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs +++ b/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs @@ -15,7 +15,6 @@ using System.Runtime.CompilerServices; using System.Threading; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.Versioning; namespace System.Threading.Tasks @@ -517,7 +516,7 @@ private static void FromAsyncCoreLogic( Task promise, bool requiresSynchronization) { - Contract.Requires((endFunction != null) != (endAction != null), "Expected exactly one of endFunction/endAction to be non-null"); + Debug.Assert((endFunction != null) != (endAction != null), "Expected exactly one of endFunction/endAction to be non-null"); Exception ex = null; OperationCanceledException oce = null; @@ -666,11 +665,10 @@ internal static Task FromAsyncImpl( if (endFunction == null && endAction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endMethod); - Contract.Requires((endFunction != null) != (endAction != null), "Both endFunction and endAction were non-null"); + Debug.Assert((endFunction != null) != (endAction != null), "Both endFunction and endAction were non-null"); if (scheduler == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); - Contract.EndContractBlock(); TaskFactory.CheckFromAsyncOptions(creationOptions, false); @@ -789,7 +787,7 @@ internal static Task FromAsyncImpl(Func FromAsyncImpl(Func FromAsyncImpl(Func FromAsyncImpl(Func : Task where TInst /// The end method. internal FromAsyncTrimPromise(TInstance thisRef, Func endMethod) : base() { - Contract.Requires(thisRef != null, "Expected a non-null thisRef"); - Contract.Requires(endMethod != null, "Expected a non-null endMethod"); + Debug.Assert(thisRef != null, "Expected a non-null thisRef"); + Debug.Assert(endMethod != null, "Expected a non-null endMethod"); m_thisRef = thisRef; m_endMethod = endMethod; } @@ -1300,7 +1298,6 @@ internal static void CompleteFromAsyncResult(IAsyncResult asyncResult) { // Validate argument if (asyncResult == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.asyncResult); - Contract.EndContractBlock(); var promise = asyncResult.AsyncState as FromAsyncTrimPromise; if (promise == null) ThrowHelper.ThrowArgumentException(ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple, ExceptionArgument.asyncResult); @@ -1403,7 +1400,6 @@ private static Task CreateCanceledTask(TaskContinuationOptions continua public Task ContinueWhenAll(Task[] tasks, Func continuationFunction) { if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); - Contract.EndContractBlock(); return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1432,7 +1428,6 @@ public Task ContinueWhenAll(Task[] tasks, Func continu public Task ContinueWhenAll(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken) { if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); - Contract.EndContractBlock(); return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -1467,7 +1462,6 @@ public Task ContinueWhenAll(Task[] tasks, Func continu public Task ContinueWhenAll(Task[] tasks, Func continuationFunction, TaskContinuationOptions continuationOptions) { if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); - Contract.EndContractBlock(); return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1513,7 +1507,6 @@ public Task ContinueWhenAll(Task[] tasks, Func continu CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); - Contract.EndContractBlock(); return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -1538,7 +1531,6 @@ public Task ContinueWhenAll(Task[] tasks, Func continu public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction) { if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); - Contract.EndContractBlock(); return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1569,7 +1561,6 @@ public Task ContinueWhenAll(Task[ CancellationToken cancellationToken) { if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); - Contract.EndContractBlock(); return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -1606,7 +1597,6 @@ public Task ContinueWhenAll(Task[ TaskContinuationOptions continuationOptions) { if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); - Contract.EndContractBlock(); return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1653,7 +1643,6 @@ public Task ContinueWhenAll(Task[ CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); - Contract.EndContractBlock(); return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -1669,9 +1658,8 @@ internal static Task ContinueWhenAllImpl(Task[] tasksCopy = TaskFactory.CheckMultiContinuationTasksAndCopy(tasks); @@ -1716,9 +1704,8 @@ internal static Task ContinueWhenAllImpl(Task[] tasks, TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions); if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); //ArgumentNullException of continuationFunction or continuationAction is checked by the caller - Contract.Requires((continuationFunction != null) != (continuationAction != null), "Expected exactly one of endFunction/endAction to be non-null"); + Debug.Assert((continuationFunction != null) != (continuationAction != null), "Expected exactly one of endFunction/endAction to be non-null"); if (scheduler == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); - Contract.EndContractBlock(); // Check tasks array and make defensive copy Task[] tasksCopy = TaskFactory.CheckMultiContinuationTasksAndCopy(tasks); @@ -1787,7 +1774,6 @@ internal static Task ContinueWhenAllImpl(Task[] tasks, public Task ContinueWhenAny(Task[] tasks, Func continuationFunction) { if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); - Contract.EndContractBlock(); return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1816,7 +1802,6 @@ public Task ContinueWhenAny(Task[] tasks, Func continuat public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken) { if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); - Contract.EndContractBlock(); return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -1851,7 +1836,6 @@ public Task ContinueWhenAny(Task[] tasks, Func continuat public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, TaskContinuationOptions continuationOptions) { if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); - Contract.EndContractBlock(); return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1897,7 +1881,6 @@ public Task ContinueWhenAny(Task[] tasks, Func continuat CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); - Contract.EndContractBlock(); return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -1922,7 +1905,6 @@ public Task ContinueWhenAny(Task[] tasks, Func continuat public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction) { if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); - Contract.EndContractBlock(); return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1953,7 +1935,6 @@ public Task ContinueWhenAny(Task[ CancellationToken cancellationToken) { if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); - Contract.EndContractBlock(); return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -1990,7 +1971,6 @@ public Task ContinueWhenAny(Task[ TaskContinuationOptions continuationOptions) { if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); - Contract.EndContractBlock(); return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2037,7 +2017,6 @@ public Task ContinueWhenAny(Task[ CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); - Contract.EndContractBlock(); return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -2054,9 +2033,8 @@ internal static Task ContinueWhenAnyImpl(Task[] tasks, if (tasks.Length == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList, ExceptionArgument.tasks); //ArgumentNullException of continuationFunction or continuationAction is checked by the caller - Contract.Requires((continuationFunction != null) != (continuationAction != null), "Expected exactly one of endFunction/endAction to be non-null"); + Debug.Assert((continuationFunction != null) != (continuationAction != null), "Expected exactly one of endFunction/endAction to be non-null"); if (scheduler == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); - Contract.EndContractBlock(); // Call common ContinueWhenAny() setup logic, extract starter Task starter = TaskFactory.CommonCWAnyLogic(tasks); @@ -2101,9 +2079,8 @@ internal static Task ContinueWhenAnyImpl(TaskThe segment in which to first attempt to store the item. private void EnqueueSlow(T item, ref Segment segment) { - Contract.Requires(segment != null, "Expected a non-null segment."); + Debug.Assert(segment != null, "Expected a non-null segment."); if (segment.m_state.m_firstCopy != segment.m_state.m_first) { @@ -220,8 +219,8 @@ public bool TryDequeue(out T result) /// true if an item could be dequeued; otherwise, false. private bool TryDequeueSlow(ref Segment segment, ref T[] array, out T result) { - Contract.Requires(segment != null, "Expected a non-null segment."); - Contract.Requires(array != null, "Expected a non-null item array."); + Debug.Assert(segment != null, "Expected a non-null segment."); + Debug.Assert(array != null, "Expected a non-null item array."); if (segment.m_state.m_last != segment.m_state.m_lastCopy) { @@ -322,7 +321,7 @@ private sealed class Segment /// The size to use for this segment. internal Segment(int size) { - Contract.Requires((size & (size - 1)) == 0, "Size must be a power of 2"); + Debug.Assert((size & (size - 1)) == 0, "Size must be a power of 2"); m_array = new T[size]; } } @@ -361,7 +360,7 @@ private sealed class SingleProducerSingleConsumerQueue_DebugView /// The queue being debugged. public SingleProducerSingleConsumerQueue_DebugView(SingleProducerSingleConsumerQueue queue) { - Contract.Requires(queue != null, "Expected a non-null queue."); + Debug.Assert(queue != null, "Expected a non-null queue."); m_queue = queue; } } diff --git a/src/mscorlib/src/System/Threading/Tasks/Task.cs b/src/mscorlib/src/System/Threading/Tasks/Task.cs index 84811fb06835..c903622d75d7 100644 --- a/src/mscorlib/src/System/Threading/Tasks/Task.cs +++ b/src/mscorlib/src/System/Threading/Tasks/Task.cs @@ -13,7 +13,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Diagnostics.Tracing; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; @@ -214,7 +213,7 @@ public class Task : IThreadPoolWorkItem, IAsyncResult, IDisposable [FriendAccessAllowed] internal static bool AddToActiveTasks(Task task) { - Contract.Requires(task != null, "Null Task objects can't be added to the ActiveTasks collection"); + Debug.Assert(task != null, "Null Task objects can't be added to the ActiveTasks collection"); lock (s_activeTasksLock) { s_currentActiveTasks[task.Id] = task; @@ -515,7 +514,6 @@ internal Task(Delegate action, object state, Task parent, CancellationToken canc { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action); } - Contract.EndContractBlock(); // Keep a link to the parent if attached if (parent != null && (creationOptions & TaskCreationOptions.AttachedToParent) != 0) @@ -1073,7 +1071,6 @@ public void RunSynchronously(TaskScheduler scheduler) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } - Contract.EndContractBlock(); InternalRunSynchronously(scheduler, waitForCompletion: true); } @@ -1083,7 +1080,7 @@ public void RunSynchronously(TaskScheduler scheduler) // internal void InternalRunSynchronously(TaskScheduler scheduler, bool waitForCompletion) { - Contract.Requires(scheduler != null, "Task.InternalRunSynchronously(): null TaskScheduler"); + Debug.Assert(scheduler != null, "Task.InternalRunSynchronously(): null TaskScheduler"); // Read the volatile m_stateFlags field once and cache it for subsequent operations int flags = m_stateFlags; @@ -1193,7 +1190,6 @@ internal static Task InternalStartNew( { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } - Contract.EndContractBlock(); // Create and schedule the task. This throws an InvalidOperationException if already shut down. // Here we add the InternalTaskOptions.QueuedByRuntime to the internalOptions, so that TaskConstructorCore can skip the cancellation token registration @@ -1810,7 +1806,7 @@ internal void ScheduleAndStart(bool needsProtection) /// An object representing either an Exception or a collection of Exceptions. internal void AddException(object exceptionObject) { - Contract.Requires(exceptionObject != null, "Task.AddException: Expected a non-null exception object"); + Debug.Assert(exceptionObject != null, "Task.AddException: Expected a non-null exception object"); AddException(exceptionObject, representsCancellation: false); } @@ -1821,7 +1817,7 @@ internal void AddException(object exceptionObject) /// Whether the exceptionObject is an OperationCanceledException representing cancellation. internal void AddException(object exceptionObject, bool representsCancellation) { - Contract.Requires(exceptionObject != null, "Task.AddException: Expected a non-null exception object"); + Debug.Assert(exceptionObject != null, "Task.AddException: Expected a non-null exception object"); #if DEBUG var eoAsException = exceptionObject as Exception; @@ -1964,7 +1960,7 @@ internal ExceptionDispatchInfo GetCancellationExceptionDispatchInfo() /// internal void ThrowIfExceptional(bool includeTaskCanceledExceptions) { - Contract.Requires(IsCompleted, "ThrowIfExceptional(): Expected IsCompleted == true"); + Debug.Assert(IsCompleted, "ThrowIfExceptional(): Expected IsCompleted == true"); Exception exception = GetExceptions(includeTaskCanceledExceptions); if (exception != null) @@ -2212,8 +2208,8 @@ internal void NotifyParentIfPotentiallyAttachedTask() /// internal void ProcessChildCompletion(Task childTask) { - Contract.Requires(childTask != null); - Contract.Requires(childTask.IsCompleted, "ProcessChildCompletion was called for an uncompleted task"); + Debug.Assert(childTask != null); + Debug.Assert(childTask.IsCompleted, "ProcessChildCompletion was called for an uncompleted task"); Debug.Assert(childTask.m_contingentProperties?.m_parent == this, "ProcessChildCompletion should only be called for a child of this task"); @@ -2512,7 +2508,7 @@ internal virtual void InnerInvoke() /// The exception that went unhandled. private void HandleException(Exception unhandledException) { - Contract.Requires(unhandledException != null); + Debug.Assert(unhandledException != null); OperationCanceledException exceptionAsOce = unhandledException as OperationCanceledException; if (exceptionAsOce != null && IsCancellationRequested && @@ -2568,7 +2564,7 @@ public ConfiguredTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) internal void SetContinuationForAwait( Action continuationAction, bool continueOnCapturedContext, bool flowExecutionContext) { - Contract.Requires(continuationAction != null); + Debug.Assert(continuationAction != null); // Create the best AwaitTaskContinuation object given the request. // If this remains null by the end of the function, we can use the @@ -2761,7 +2757,6 @@ public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.millisecondsTimeout); } - Contract.EndContractBlock(); // Return immediately if we know that we've completed "clean" -- no exceptions, no cancellations // and if no notification to the debugger is required @@ -2992,7 +2987,7 @@ private bool SpinWait(int millisecondsTimeout) /// true if the task was successfully canceled; otherwise, false. internal bool InternalCancel(bool bCancelNonExecutingOnly) { - Contract.Requires((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) == 0, "Task.InternalCancel() did not expect promise-style task"); + Debug.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) == 0, "Task.InternalCancel() did not expect promise-style task"); bool bPopSucceeded = false; bool mustCleanup = false; @@ -3505,7 +3500,6 @@ private Task ContinueWith(Action continuationAction, TaskScheduler schedul { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } - Contract.EndContractBlock(); TaskCreationOptions creationOptions; InternalTaskOptions internalOptions; @@ -3696,7 +3690,6 @@ private Task ContinueWith(Action continuationAction, Object state, { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } - Contract.EndContractBlock(); TaskCreationOptions creationOptions; InternalTaskOptions internalOptions; @@ -3900,7 +3893,6 @@ private Task ContinueWith(Func continuationFunc { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } - Contract.EndContractBlock(); TaskCreationOptions creationOptions; InternalTaskOptions internalOptions; @@ -4108,7 +4100,6 @@ private Task ContinueWith(Func continua { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } - Contract.EndContractBlock(); TaskCreationOptions creationOptions; InternalTaskOptions internalOptions; @@ -4195,9 +4186,9 @@ internal void ContinueWithCore(Task continuationTask, CancellationToken cancellationToken, TaskContinuationOptions options) { - Contract.Requires(continuationTask != null, "Task.ContinueWithCore(): null continuationTask"); - Contract.Requires(scheduler != null, "Task.ContinueWithCore(): null scheduler"); - Contract.Requires(!continuationTask.IsCompleted, "Did not expect continuationTask to be completed"); + Debug.Assert(continuationTask != null, "Task.ContinueWithCore(): null continuationTask"); + Debug.Assert(scheduler != null, "Task.ContinueWithCore(): null scheduler"); + Debug.Assert(!continuationTask.IsCompleted, "Did not expect continuationTask to be completed"); // Create a TaskContinuation TaskContinuation continuation = new StandardTaskContinuation(continuationTask, options, scheduler); @@ -4288,7 +4279,7 @@ private void AddCompletionAction(ITaskCompletionAction action, bool addBeforeOth // care of in the calling method, AddTaskContinuation(). private bool AddTaskContinuationComplex(object tc, bool addBeforeOthers) { - Contract.Requires(tc != null, "Expected non-null tc object in AddTaskContinuationComplex"); + Debug.Assert(tc != null, "Expected non-null tc object in AddTaskContinuationComplex"); object oldValue = m_continuationObject; @@ -4352,7 +4343,7 @@ private bool AddTaskContinuationComplex(object tc, bool addBeforeOthers) // Return true if and only if we successfully queued a continuation. private bool AddTaskContinuation(object tc, bool addBeforeOthers) { - Contract.Requires(tc != null); + Debug.Assert(tc != null); // Make sure that, if someone calls ContinueWith() right after waiting for the predecessor to complete, // we don't queue up a continuation. @@ -4613,7 +4604,6 @@ private static bool WaitAllCore(Task[] tasks, int millisecondsTimeout, Cancellat { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.millisecondsTimeout); } - Contract.EndContractBlock(); cancellationToken.ThrowIfCancellationRequested(); // early check before we make any allocations @@ -4990,7 +4980,6 @@ private static int WaitAnyCore(Task[] tasks, int millisecondsTimeout, Cancellati { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.millisecondsTimeout); } - Contract.EndContractBlock(); cancellationToken.ThrowIfCancellationRequested(); // early check before we make any allocations @@ -5068,7 +5057,6 @@ public static Task FromException(Exception exception) public static Task FromException(Exception exception) { if (exception == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception); - Contract.EndContractBlock(); var task = new Task(); bool succeeded = task.TrySetException(exception); @@ -5083,7 +5071,6 @@ public static Task FromCanceled(CancellationToken cancellationToken) { if (!cancellationToken.IsCancellationRequested) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.cancellationToken); - Contract.EndContractBlock(); return new Task(true, TaskCreationOptions.None, cancellationToken); } @@ -5095,7 +5082,6 @@ public static Task FromCanceled(CancellationToken cancellation { if (!cancellationToken.IsCancellationRequested) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.cancellationToken); - Contract.EndContractBlock(); return new Task(true, default(TResult), TaskCreationOptions.None, cancellationToken); } @@ -5106,7 +5092,6 @@ public static Task FromCanceled(CancellationToken cancellation internal static Task FromCancellation(OperationCanceledException exception) { if (exception == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception); - Contract.EndContractBlock(); var task = new Task(); bool succeeded = task.TrySetCanceled(exception.CancellationToken, exception); @@ -5234,7 +5219,6 @@ public static Task Run(Func function, CancellationToken cancellationToken) { // Check arguments if (function == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.function); - Contract.EndContractBlock(); // Short-circuit if we are given a pre-canceled token if (cancellationToken.IsCancellationRequested) @@ -5280,7 +5264,6 @@ public static Task Run(Func> function, Cancellat { // Check arguments if (function == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.function); - Contract.EndContractBlock(); // Short-circuit if we are given a pre-canceled token if (cancellationToken.IsCancellationRequested) @@ -5385,7 +5368,6 @@ public static Task Delay(int millisecondsDelay, CancellationToken cancellationTo { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.millisecondsDelay, ExceptionResource.Task_Delay_InvalidMillisecondsDelay); } - Contract.EndContractBlock(); // some short-cuts in case quick completion is in order if (cancellationToken.IsCancellationRequested) @@ -5565,7 +5547,6 @@ public static Task WhenAll(params Task[] tasks) { // Do some argument checking and make a defensive copy of the tasks array if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); - Contract.EndContractBlock(); int taskCount = tasks.Length; if (taskCount == 0) return InternalWhenAll(tasks); // Small optimization in the case of an empty array. @@ -5586,7 +5567,7 @@ public static Task WhenAll(params Task[] tasks) // tasks should be a defensive copy. private static Task InternalWhenAll(Task[] tasks) { - Contract.Requires(tasks != null, "Expected a non-null tasks array"); + Debug.Assert(tasks != null, "Expected a non-null tasks array"); return (tasks.Length == 0) ? // take shortcut if there are no tasks upon which to wait Task.CompletedTask : new WhenAllPromise(tasks); @@ -5617,8 +5598,8 @@ private sealed class WhenAllPromise : Task, ITaskCompletionActio internal WhenAllPromise(Task[] tasks) : base() { - Contract.Requires(tasks != null, "Expected a non-null task array"); - Contract.Requires(tasks.Length > 0, "Expected a non-zero length task array"); + Debug.Assert(tasks != null, "Expected a non-null task array"); + Debug.Assert(tasks.Length > 0, "Expected a non-zero length task array"); if (AsyncCausalityTracer.LoggingOn) AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, this.Id, "Task.WhenAll", 0); @@ -5819,7 +5800,6 @@ public static Task WhenAll(params Task[] tasks) { // Do some argument checking and make a defensive copy of the tasks array if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); - Contract.EndContractBlock(); int taskCount = tasks.Length; if (taskCount == 0) return InternalWhenAll(tasks); // small optimization in the case of an empty task array @@ -5839,7 +5819,7 @@ public static Task WhenAll(params Task[] tasks) // Some common logic to support WhenAll methods private static Task InternalWhenAll(Task[] tasks) { - Contract.Requires(tasks != null, "Expected a non-null tasks array"); + Debug.Assert(tasks != null, "Expected a non-null tasks array"); return (tasks.Length == 0) ? // take shortcut if there are no tasks upon which to wait new Task(false, new TResult[0], TaskCreationOptions.None, default(CancellationToken)) : new WhenAllPromise(tasks); @@ -5863,8 +5843,8 @@ private sealed class WhenAllPromise : Task, ITaskCompletionAction internal WhenAllPromise(Task[] tasks) : base() { - Contract.Requires(tasks != null, "Expected a non-null task array"); - Contract.Requires(tasks.Length > 0, "Expected a non-zero length task array"); + Debug.Assert(tasks != null, "Expected a non-null task array"); + Debug.Assert(tasks.Length > 0, "Expected a non-zero length task array"); m_tasks = tasks; m_count = tasks.Length; @@ -5995,7 +5975,6 @@ public static Task WhenAny(params Task[] tasks) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList, ExceptionArgument.tasks); } - Contract.EndContractBlock(); // Make a defensive copy, as the user may manipulate the tasks array // after we return but before the WhenAny asynchronously completes. @@ -6030,7 +6009,6 @@ public static Task WhenAny(params Task[] tasks) public static Task WhenAny(IEnumerable tasks) { if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); - Contract.EndContractBlock(); // Make a defensive copy, as the user may manipulate the tasks collection // after we return but before the WhenAny asynchronously completes. @@ -6112,7 +6090,7 @@ public static Task> WhenAny(IEnumerable> ta [FriendAccessAllowed] internal static Task CreateUnwrapPromise(Task outerTask, bool lookForOce) { - Contract.Requires(outerTask != null); + Debug.Assert(outerTask != null); return new UnwrapPromise(outerTask, lookForOce); } @@ -6516,7 +6494,7 @@ internal sealed class UnwrapPromise : Task, ITaskCompletionAct public UnwrapPromise(Task outerTask, bool lookForOce) : base((object)null, outerTask.CreationOptions & TaskCreationOptions.AttachedToParent) { - Contract.Requires(outerTask != null, "Expected non-null outerTask"); + Debug.Assert(outerTask != null, "Expected non-null outerTask"); _lookForOce = lookForOce; _state = STATE_WAITING_ON_OUTER_TASK; @@ -6601,7 +6579,7 @@ private void InvokeCoreAsync(Task completingTask) /// The now-completed outer task. private void ProcessCompletedOuterTask(Task task) { - Contract.Requires(task != null && task.IsCompleted, "Expected non-null, completed outer task"); + Debug.Assert(task != null && task.IsCompleted, "Expected non-null, completed outer task"); Debug.Assert(_state == STATE_WAITING_ON_OUTER_TASK, "We're in the wrong state!"); // Bump our state before proceeding any further @@ -6632,7 +6610,7 @@ private void ProcessCompletedOuterTask(Task task) /// true if the transfer was successful; otherwise, false. private bool TrySetFromTask(Task task, bool lookForOce) { - Contract.Requires(task != null && task.IsCompleted, "TrySetFromTask: Expected task to have completed."); + Debug.Assert(task != null && task.IsCompleted, "TrySetFromTask: Expected task to have completed."); if (AsyncCausalityTracer.LoggingOn) AsyncCausalityTracer.TraceOperationRelation(CausalityTraceLevel.Important, this.Id, CausalityRelation.Join); diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs b/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs index 47a51a45f53e..dc59caf04fd0 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs @@ -13,7 +13,6 @@ using System; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs b/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs index de222352c9d9..06539f956c3a 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs @@ -12,7 +12,6 @@ using System.Security; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.ExceptionServices; using System.Runtime.CompilerServices; using System.Threading; @@ -32,7 +31,7 @@ public ContinuationTaskFromTask( Task antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null) { - Contract.Requires(action is Action || action is Action, + Debug.Assert(action is Action || action is Action, "Invalid delegate type in ContinuationTaskFromTask"); m_antecedent = antecedent; } @@ -79,7 +78,7 @@ public ContinuationResultTaskFromTask( Task antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null) { - Contract.Requires(function is Func || function is Func, + Debug.Assert(function is Func || function is Func, "Invalid delegate type in ContinuationResultTaskFromTask"); m_antecedent = antecedent; } @@ -126,7 +125,7 @@ public ContinuationTaskFromResultTask( Task antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null) { - Contract.Requires(action is Action> || action is Action, object>, + Debug.Assert(action is Action> || action is Action, object>, "Invalid delegate type in ContinuationTaskFromResultTask"); m_antecedent = antecedent; } @@ -173,7 +172,7 @@ public ContinuationResultTaskFromResultTask( Task antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null) { - Contract.Requires(function is Func, TResult> || function is Func, object, TResult>, + Debug.Assert(function is Func, TResult> || function is Func, object, TResult>, "Invalid delegate type in ContinuationResultTaskFromResultTask"); m_antecedent = antecedent; } @@ -234,7 +233,7 @@ internal abstract class TaskContinuation /// protected static void InlineIfPossibleOrElseQueue(Task task, bool needsProtection) { - Contract.Requires(task != null); + Debug.Assert(task != null); Debug.Assert(task.m_taskScheduler != null); // Set the TASK_STATE_STARTED flag. This only needs to be done @@ -294,8 +293,8 @@ internal class StandardTaskContinuation : TaskContinuation /// The scheduler to use for the continuation. internal StandardTaskContinuation(Task task, TaskContinuationOptions options, TaskScheduler scheduler) { - Contract.Requires(task != null, "TaskContinuation ctor: task is null"); - Contract.Requires(scheduler != null, "TaskContinuation ctor: scheduler is null"); + Debug.Assert(task != null, "TaskContinuation ctor: task is null"); + Debug.Assert(scheduler != null, "TaskContinuation ctor: scheduler is null"); m_task = task; m_options = options; m_taskScheduler = scheduler; @@ -539,7 +538,7 @@ internal class AwaitTaskContinuation : TaskContinuation, IThreadPoolWorkItem /// Whether to capture and restore ExecutionContext. internal AwaitTaskContinuation(Action action, bool flowExecutionContext) { - Contract.Requires(action != null); + Debug.Assert(action != null); m_action = action; if (flowExecutionContext) { @@ -554,8 +553,8 @@ internal AwaitTaskContinuation(Action action, bool flowExecutionContext) /// The created task. protected Task CreateTask(Action action, object state, TaskScheduler scheduler) { - Contract.Requires(action != null); - Contract.Requires(scheduler != null); + Debug.Assert(action != null); + Debug.Assert(scheduler != null); return new Task( action, state, null, default(CancellationToken), @@ -699,7 +698,7 @@ protected static ContextCallback GetInvokeActionCallback() /// A reference to Task.t_currentTask. protected void RunCallback(ContextCallback callback, object state, ref Task currentTask) { - Contract.Requires(callback != null); + Debug.Assert(callback != null); Debug.Assert(currentTask == Task.t_currentTask); // Pretend there's no current task, so that no task is seen as a parent diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs b/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs index 1385d907e096..a96852a6f00d 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs @@ -19,7 +19,6 @@ namespace System.Threading.Tasks using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; - using System.Diagnostics.Contracts; using System.Runtime.ExceptionServices; using System.Security; @@ -58,7 +57,7 @@ internal class TaskExceptionHolder /// The task this holder belongs to. internal TaskExceptionHolder(Task task) { - Contract.Requires(task != null, "Expected a non-null task."); + Debug.Assert(task != null, "Expected a non-null task."); m_task = task; EnsureADUnloadCallbackRegistered(); } @@ -162,8 +161,8 @@ private static void AppDomainUnloadCallback(object sender, EventArgs e) /// internal void Add(object exceptionObject, bool representsCancellation) { - Contract.Requires(exceptionObject != null, "TaskExceptionHolder.Add(): Expected a non-null exceptionObject"); - Contract.Requires( + Debug.Assert(exceptionObject != null, "TaskExceptionHolder.Add(): Expected a non-null exceptionObject"); + Debug.Assert( exceptionObject is Exception || exceptionObject is IEnumerable || exceptionObject is ExceptionDispatchInfo || exceptionObject is IEnumerable, "TaskExceptionHolder.Add(): Expected Exception, IEnumerable, ExceptionDispatchInfo, or IEnumerable"); @@ -179,7 +178,7 @@ exceptionObject is Exception || exceptionObject is IEnumerable || /// private void SetCancellationException(object exceptionObject) { - Contract.Requires(exceptionObject != null, "Expected exceptionObject to be non-null."); + Debug.Assert(exceptionObject != null, "Expected exceptionObject to be non-null."); Debug.Assert(m_cancellationException == null, "Expected SetCancellationException to be called only once."); @@ -216,7 +215,7 @@ private void SetCancellationException(object exceptionObject) /// private void AddFaultException(object exceptionObject) { - Contract.Requires(exceptionObject != null, "AddFaultException(): Expected a non-null exceptionObject"); + Debug.Assert(exceptionObject != null, "AddFaultException(): Expected a non-null exceptionObject"); // Initialize the exceptions list if necessary. The list should be non-null iff it contains exceptions. var exceptions = m_faultExceptions; diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs b/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs index e193d0e4e20d..875d47b1e7b4 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs @@ -18,7 +18,6 @@ using System.Runtime.CompilerServices; using System.Threading; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Threading.Tasks { @@ -202,7 +201,6 @@ public TaskFactory(CancellationToken cancellationToken, TaskCreationOptions crea m_defaultContinuationOptions = continuationOptions; } - [ContractArgumentValidatorAttribute] internal static void CheckCreationOptions(TaskCreationOptions creationOptions) { // Check for validity of options @@ -216,7 +214,6 @@ internal static void CheckCreationOptions(TaskCreationOptions creationOptions) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.creationOptions); } - Contract.EndContractBlock(); } /* Properties */ @@ -1560,7 +1557,7 @@ private sealed class CompleteOnCountdownPromise : Task, ITaskCompletionA internal CompleteOnCountdownPromise(Task[] tasksCopy) : base() { - Contract.Requires((tasksCopy != null) && (tasksCopy.Length > 0), "Expected non-null task array with at least one element in it"); + Debug.Assert((tasksCopy != null) && (tasksCopy.Length > 0), "Expected non-null task array with at least one element in it"); _tasks = tasksCopy; _count = tasksCopy.Length; @@ -1614,7 +1611,7 @@ internal override bool ShouldNotifyDebuggerOfWaitCompletion // Performs some logic common to all ContinueWhenAll() overloads internal static Task CommonCWAllLogic(Task[] tasksCopy) { - Contract.Requires(tasksCopy != null); + Debug.Assert(tasksCopy != null); // Create a promise task to be returned to the user CompleteOnCountdownPromise promise = new CompleteOnCountdownPromise(tasksCopy); @@ -1640,7 +1637,7 @@ private sealed class CompleteOnCountdownPromise : Task[]>, ITaskCompl internal CompleteOnCountdownPromise(Task[] tasksCopy) : base() { - Contract.Requires((tasksCopy != null) && (tasksCopy.Length > 0), "Expected non-null task array with at least one element in it"); + Debug.Assert((tasksCopy != null) && (tasksCopy.Length > 0), "Expected non-null task array with at least one element in it"); _tasks = tasksCopy; _count = tasksCopy.Length; @@ -1694,7 +1691,7 @@ internal override bool ShouldNotifyDebuggerOfWaitCompletion internal static Task[]> CommonCWAllLogic(Task[] tasksCopy) { - Contract.Requires(tasksCopy != null); + Debug.Assert(tasksCopy != null); // Create a promise task to be returned to the user CompleteOnCountdownPromise promise = new CompleteOnCountdownPromise(tasksCopy); @@ -1726,7 +1723,6 @@ internal static Task[]> CommonCWAllLogic(Task[] tasksCopy) public Task ContinueWhenAll(Task[] tasks, Action continuationAction) { if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1756,7 +1752,6 @@ public Task ContinueWhenAll(Task[] tasks, Action continuationAction) public Task ContinueWhenAll(Task[] tasks, Action continuationAction, CancellationToken cancellationToken) { if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -1791,7 +1786,6 @@ public Task ContinueWhenAll(Task[] tasks, Action continuationAction, Can public Task ContinueWhenAll(Task[] tasks, Action continuationAction, TaskContinuationOptions continuationOptions) { if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1837,7 +1831,6 @@ public Task ContinueWhenAll(Task[] tasks, Action continuationAction, Can TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } @@ -1862,7 +1855,6 @@ public Task ContinueWhenAll(Task[] tasks, Action continuationAction, Can public Task ContinueWhenAll(Task[] tasks, Action[]> continuationAction) { if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1894,7 +1886,6 @@ public Task ContinueWhenAll(Task[] tasks, CancellationToken cancellationToken) { if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -1931,7 +1922,6 @@ public Task ContinueWhenAll(Task[] tasks, TaskContinuationOptions continuationOptions) { if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1978,7 +1968,6 @@ public Task ContinueWhenAll(Task[] tasks, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } @@ -2006,7 +1995,6 @@ public Task ContinueWhenAll(Task[] tasks, public Task ContinueWhenAll(Task[] tasks, Func continuationFunction) { if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2040,7 +2028,6 @@ public Task ContinueWhenAll(Task[] tasks, Func ContinueWhenAll(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken) { if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2079,7 +2066,6 @@ public Task ContinueWhenAll(Task[] tasks, Func ContinueWhenAll(Task[] tasks, Func continuationFunction, TaskContinuationOptions continuationOptions) { if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2129,7 +2115,6 @@ public Task ContinueWhenAll(Task[] tasks, Func.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -2159,7 +2144,6 @@ public Task ContinueWhenAll(Task[] tasks, Func ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction) { if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2194,7 +2178,6 @@ public Task ContinueWhenAll(Task.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2235,7 +2218,6 @@ public Task ContinueWhenAll(Task.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2286,7 +2268,6 @@ public Task ContinueWhenAll(Task.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -2313,7 +2294,7 @@ internal sealed class CompleteOnInvokePromise : Task, ITaskCompletionActio public CompleteOnInvokePromise(IList tasks) : base() { - Contract.Requires(tasks != null, "Expected non-null collection of tasks"); + Debug.Assert(tasks != null, "Expected non-null collection of tasks"); _tasks = tasks; if (AsyncCausalityTracer.LoggingOn) @@ -2370,7 +2351,7 @@ public void Invoke(Task completingTask) // asynchronously (e.g. WhenAny) rather than synchronously (e.g. WaitAny). internal static Task CommonCWAnyLogic(IList tasks) { - Contract.Requires(tasks != null); + Debug.Assert(tasks != null); // Create a promise task to be returned to the user. // (If this logic ever changes, also update CommonCWAnyLogicCleanup.) @@ -2452,7 +2433,6 @@ internal static void CommonCWAnyLogicCleanup(Task continuation) public Task ContinueWhenAny(Task[] tasks, Action continuationAction) { if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2481,7 +2461,6 @@ public Task ContinueWhenAny(Task[] tasks, Action continuationAction) public Task ContinueWhenAny(Task[] tasks, Action continuationAction, CancellationToken cancellationToken) { if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2516,7 +2495,6 @@ public Task ContinueWhenAny(Task[] tasks, Action continuationAction, Cance public Task ContinueWhenAny(Task[] tasks, Action continuationAction, TaskContinuationOptions continuationOptions) { if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2562,7 +2540,6 @@ public Task ContinueWhenAny(Task[] tasks, Action continuationAction, Cance TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } @@ -2591,7 +2568,6 @@ public Task ContinueWhenAny(Task[] tasks, Action continuationAction, Cance public Task ContinueWhenAny(Task[] tasks, Func continuationFunction) { if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2624,7 +2600,6 @@ public Task ContinueWhenAny(Task[] tasks, Func public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken) { if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2663,7 +2638,6 @@ public Task ContinueWhenAny(Task[] tasks, Func public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, TaskContinuationOptions continuationOptions) { if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2713,7 +2687,6 @@ public Task ContinueWhenAny(Task[] tasks, Func TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -2775,7 +2748,6 @@ public Task ContinueWhenAny(Task.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2816,7 +2788,6 @@ public Task ContinueWhenAny(Task.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2867,7 +2838,6 @@ public Task ContinueWhenAny(Task.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -2893,7 +2863,6 @@ public Task ContinueWhenAny(Task(Task[] tasks, Action> continuationAction) { if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2924,7 +2893,6 @@ public Task ContinueWhenAny(Task[] tasks, CancellationToken cancellationToken) { if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2961,7 +2929,6 @@ public Task ContinueWhenAny(Task[] tasks, TaskContinuationOptions continuationOptions) { if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -3008,7 +2975,6 @@ public Task ContinueWhenAny(Task[] tasks, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - Contract.EndContractBlock(); return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } @@ -3021,7 +2987,6 @@ internal static Task[] CheckMultiContinuationTasksAndCopy(Task[] tasks) throw new ArgumentNullException(nameof(tasks)); if (tasks.Length == 0) throw new ArgumentException(SR.Task_MultiTaskContinuation_EmptyTaskList, nameof(tasks)); - Contract.EndContractBlock(); Task[] tasksCopy = new Task[tasks.Length]; for (int i = 0; i < tasks.Length; i++) @@ -3041,7 +3006,6 @@ internal static Task[] CheckMultiContinuationTasksAndCopy(Task throw new ArgumentNullException(nameof(tasks)); if (tasks.Length == 0) throw new ArgumentException(SR.Task_MultiTaskContinuation_EmptyTaskList, nameof(tasks)); - Contract.EndContractBlock(); Task[] tasksCopy = new Task[tasks.Length]; for (int i = 0; i < tasks.Length; i++) @@ -3056,7 +3020,6 @@ internal static Task[] CheckMultiContinuationTasksAndCopy(Task } // Throw an exception if "options" argument specifies illegal options - [ContractArgumentValidatorAttribute] internal static void CheckMultiTaskContinuationOptions(TaskContinuationOptions continuationOptions) { // Construct a mask to check for illegal options @@ -3088,7 +3051,6 @@ internal static void CheckMultiTaskContinuationOptions(TaskContinuationOptions c // Check that no "fire" options are specified. if ((continuationOptions & NotOnAny) != 0) throw new ArgumentOutOfRangeException(nameof(continuationOptions), SR.Task_MultiTaskContinuation_FireOptions); - Contract.EndContractBlock(); } } } diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs b/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs index eddaeee9d7eb..e1fda2530de3 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs @@ -18,7 +18,6 @@ using System.Threading; using System.Security; using System.Collections.Concurrent; -using System.Diagnostics.Contracts; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -257,7 +256,7 @@ internal virtual bool RequiresAtomicStartTransition /// internal void InternalQueueTask(Task task) { - Contract.Requires(task != null); + Debug.Assert(task != null); if (TplEtwProvider.Log.IsEnabled()) { diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs b/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs index fdd62c95f5a2..7e22dfa66dd4 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs @@ -23,7 +23,6 @@ using System.IO; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Threading.Tasks { @@ -42,7 +41,7 @@ internal static class TaskToApm /// An IAsyncResult to represent the task's asynchronous operation. public static IAsyncResult Begin(Task task, AsyncCallback callback, object state) { - Contract.Requires(task != null); + Debug.Assert(task != null); // If the task has already completed, then since the Task's CompletedSynchronously==false // and we want it to be true, we need to create a new IAsyncResult. (We also need the AsyncState to match.) @@ -122,9 +121,9 @@ public static TResult End(IAsyncResult asyncResult) /// The Task used as the IAsyncResult. private static void InvokeCallbackWhenTaskCompletes(Task antecedent, AsyncCallback callback, IAsyncResult asyncResult) { - Contract.Requires(antecedent != null); - Contract.Requires(callback != null); - Contract.Requires(asyncResult != null); + Debug.Assert(antecedent != null); + Debug.Assert(callback != null); + Debug.Assert(asyncResult != null); // We use OnCompleted rather than ContinueWith in order to avoid running synchronously // if the task has already completed by the time we get here. This is separated out into @@ -169,8 +168,8 @@ private sealed class TaskWrapperAsyncResult : IAsyncResult /// The new CompletedSynchronously value. internal TaskWrapperAsyncResult(Task task, object state, bool completedSynchronously) { - Contract.Requires(task != null); - Contract.Requires(!completedSynchronously || task.IsCompleted, "If completedSynchronously is true, the task must be completed."); + Debug.Assert(task != null); + Debug.Assert(!completedSynchronously || task.IsCompleted, "If completedSynchronously is true, the task must be completed."); this.Task = task; m_state = state; diff --git a/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs b/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs index e69a89fe6686..87d6d7b5238d 100644 --- a/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs +++ b/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs @@ -14,7 +14,6 @@ using System; using System.Security; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Collections.Generic; using System.Text; diff --git a/src/mscorlib/src/System/Threading/Tasks/future.cs b/src/mscorlib/src/System/Threading/Tasks/future.cs index bf9000ea00bb..d114f892f0a6 100644 --- a/src/mscorlib/src/System/Threading/Tasks/future.cs +++ b/src/mscorlib/src/System/Threading/Tasks/future.cs @@ -18,7 +18,6 @@ using System.Security; using System.Threading; using System.Diagnostics; -using System.Diagnostics.Contracts; // Disable the "reference to volatile field not treated as volatile" error. #pragma warning disable 0420 diff --git a/src/mscorlib/src/System/Threading/Thread.cs b/src/mscorlib/src/System/Threading/Thread.cs index d8ea6410ebec..22984d94c51f 100644 --- a/src/mscorlib/src/System/Threading/Thread.cs +++ b/src/mscorlib/src/System/Threading/Thread.cs @@ -28,7 +28,6 @@ namespace System.Threading using System.Security; using System.Runtime.Versioning; using System.Diagnostics; - using System.Diagnostics.Contracts; internal delegate Object InternalCrossContextDelegate(Object[] args); @@ -166,7 +165,6 @@ public Thread(ThreadStart start) { throw new ArgumentNullException(nameof(start)); } - Contract.EndContractBlock(); SetStartHelper((Delegate)start, 0); //0 will setup Thread with default stackSize } @@ -178,7 +176,6 @@ internal Thread(ThreadStart start, int maxStackSize) } if (0 > maxStackSize) throw new ArgumentOutOfRangeException(nameof(maxStackSize), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); SetStartHelper((Delegate)start, maxStackSize); } public Thread(ParameterizedThreadStart start) @@ -187,7 +184,6 @@ public Thread(ParameterizedThreadStart start) { throw new ArgumentNullException(nameof(start)); } - Contract.EndContractBlock(); SetStartHelper((Delegate)start, 0); } @@ -199,7 +195,6 @@ internal Thread(ParameterizedThreadStart start, int maxStackSize) } if (0 > maxStackSize) throw new ArgumentOutOfRangeException(nameof(maxStackSize), SR.ArgumentOutOfRange_NeedNonNegNum); - Contract.EndContractBlock(); SetStartHelper((Delegate)start, maxStackSize); } @@ -354,7 +349,6 @@ a explict busy loop because the hardware can be informed that it is busy waiting { get { - Contract.Ensures(Contract.Result() != null); return GetCurrentThreadNative(); } } @@ -439,7 +433,6 @@ public CultureInfo CurrentUICulture { get { - Contract.Ensures(Contract.Result() != null); return CultureInfo.CurrentUICulture; } @@ -473,14 +466,11 @@ public CultureInfo CurrentCulture { get { - Contract.Ensures(Contract.Result() != null); return CultureInfo.CurrentCulture; } set { - Contract.EndContractBlock(); - // If you add more pre-conditions to this method, check to see if you also need to // add them to CultureInfo.DefaultThreadCurrentCulture.set. @@ -506,8 +496,6 @@ public CultureInfo CurrentCulture internal static AppDomain GetDomain() { - Contract.Ensures(Contract.Result() != null); - AppDomain ad; ad = GetFastDomainInternal(); diff --git a/src/mscorlib/src/System/Threading/ThreadLocal.cs b/src/mscorlib/src/System/Threading/ThreadLocal.cs index cdfa2448c012..6c823d55737d 100644 --- a/src/mscorlib/src/System/Threading/ThreadLocal.cs +++ b/src/mscorlib/src/System/Threading/ThreadLocal.cs @@ -17,7 +17,6 @@ using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System.Threading { diff --git a/src/mscorlib/src/System/Threading/ThreadPool.cs b/src/mscorlib/src/System/Threading/ThreadPool.cs index fa1dd095c0b9..61270970e91c 100644 --- a/src/mscorlib/src/System/Threading/ThreadPool.cs +++ b/src/mscorlib/src/System/Threading/ThreadPool.cs @@ -15,7 +15,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.Contracts; using System.Diagnostics.Tracing; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; @@ -1183,7 +1182,6 @@ public static RegisteredWaitHandle RegisterWaitForSingleObject( // throws Regis { if (millisecondsTimeOutInterval < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, true); } @@ -1199,7 +1197,6 @@ public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( // throws { if (millisecondsTimeOutInterval < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, false); } @@ -1215,7 +1212,6 @@ public static RegisteredWaitHandle RegisterWaitForSingleObject( // throws Regis { if (millisecondsTimeOutInterval < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, true); } @@ -1231,7 +1227,6 @@ public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( // throws { if (millisecondsTimeOutInterval < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, false); } diff --git a/src/mscorlib/src/System/Threading/Timer.cs b/src/mscorlib/src/System/Threading/Timer.cs index a5c794586436..918cbd85988d 100644 --- a/src/mscorlib/src/System/Threading/Timer.cs +++ b/src/mscorlib/src/System/Threading/Timer.cs @@ -14,7 +14,6 @@ namespace System.Threading using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics; - using System.Diagnostics.Contracts; using System.Diagnostics.Tracing; using Microsoft.Win32.SafeHandles; @@ -681,7 +680,6 @@ public Timer(TimerCallback callback, throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (period < -1) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - Contract.EndContractBlock(); TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period); } @@ -728,7 +726,6 @@ public Timer(TimerCallback callback, throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_TimeoutTooLarge); if (period > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge); - Contract.EndContractBlock(); TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period); } @@ -749,7 +746,6 @@ private void TimerSetup(TimerCallback callback, { if (callback == null) throw new ArgumentNullException(nameof(TimerCallback)); - Contract.EndContractBlock(); m_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period)); } @@ -760,7 +756,6 @@ public bool Change(int dueTime, int period) throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (period < -1) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - Contract.EndContractBlock(); return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period); } @@ -786,7 +781,6 @@ public bool Change(long dueTime, long period) throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_TimeoutTooLarge); if (period > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge); - Contract.EndContractBlock(); return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period); } @@ -795,7 +789,6 @@ public bool Dispose(WaitHandle notifyObject) { if (notifyObject == null) throw new ArgumentNullException(nameof(notifyObject)); - Contract.EndContractBlock(); return m_timer.Close(notifyObject); } diff --git a/src/mscorlib/src/System/Threading/WaitHandle.cs b/src/mscorlib/src/System/Threading/WaitHandle.cs index d91b48826522..125a29ed6cea 100644 --- a/src/mscorlib/src/System/Threading/WaitHandle.cs +++ b/src/mscorlib/src/System/Threading/WaitHandle.cs @@ -21,7 +21,6 @@ namespace System.Threading using Microsoft.Win32.SafeHandles; using System.Runtime.Versioning; using System.Runtime.ConstrainedExecution; - using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; using Win32Native = Microsoft.Win32.Win32Native; @@ -154,7 +153,6 @@ public virtual bool WaitOne(int millisecondsTimeout, bool exitContext) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } - Contract.EndContractBlock(); return WaitOne((long)millisecondsTimeout, exitContext); } @@ -196,7 +194,6 @@ internal static bool InternalWaitOne(SafeHandle waitableSafeHandle, long millise { throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic); } - Contract.EndContractBlock(); int ret = WaitOneNative(waitableSafeHandle, (uint)millisecondsTimeout, hasThreadAffinity, exitContext); if (ret == WAIT_ABANDONED) @@ -214,7 +211,6 @@ internal bool WaitOneWithoutFAS() { throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic); } - Contract.EndContractBlock(); long timeout = -1; int ret = WaitOneNative(safeWaitHandle, (uint)timeout, hasThreadAffinity, false); @@ -267,7 +263,6 @@ public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bo { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } - Contract.EndContractBlock(); WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length]; for (int i = 0; i < waitHandles.Length; i++) { @@ -357,7 +352,6 @@ public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, boo { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } - Contract.EndContractBlock(); WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length]; for (int i = 0; i < waitHandles.Length; i++) { @@ -484,7 +478,6 @@ public static bool SignalAndWait( { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } - Contract.EndContractBlock(); //NOTE: This API is not supporting Pause/Resume as it's not exposed in CoreCLR (not in WP or SL) int ret = SignalAndWaitOne(toSignal.safeWaitHandle, toWaitOn.safeWaitHandle, millisecondsTimeout, diff --git a/src/mscorlib/src/System/ThrowHelper.cs b/src/mscorlib/src/System/ThrowHelper.cs index 6c5ce05b7fec..876f5926e714 100644 --- a/src/mscorlib/src/System/ThrowHelper.cs +++ b/src/mscorlib/src/System/ThrowHelper.cs @@ -39,11 +39,9 @@ using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System { - [Pure] internal static class ThrowHelper { internal static void ThrowArrayTypeMismatchException() diff --git a/src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs b/src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs index 3cab928749b6..0e949a30ec4a 100644 --- a/src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs +++ b/src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System @@ -185,7 +184,6 @@ private static void ValidateAdjustmentRule( { throw new ArgumentException(SR.Argument_DateTimeHasTimeOfDay, nameof(dateEnd)); } - Contract.EndContractBlock(); } void IDeserializationCallback.OnDeserialization(object sender) @@ -210,7 +208,6 @@ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext contex { throw new ArgumentNullException(nameof(info)); } - Contract.EndContractBlock(); info.AddValue("DateStart", _dateStart); // Do not rename (binary serialization) info.AddValue("DateEnd", _dateEnd); // Do not rename (binary serialization) diff --git a/src/mscorlib/src/System/TimeZoneInfo.TransitionTime.cs b/src/mscorlib/src/System/TimeZoneInfo.TransitionTime.cs index 90304c92ea2b..81c0957f9a8a 100644 --- a/src/mscorlib/src/System/TimeZoneInfo.TransitionTime.cs +++ b/src/mscorlib/src/System/TimeZoneInfo.TransitionTime.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System @@ -31,7 +30,6 @@ public struct TransitionTime : IEquatable, ISerializable, IDeser public bool IsFixedDateRule => _isFixedDateRule; - [Pure] public override bool Equals(object obj) => obj is TransitionTime && Equals((TransitionTime)obj); @@ -39,7 +37,6 @@ public override bool Equals(object obj) => public static bool operator !=(TransitionTime t1, TransitionTime t2) => !t1.Equals(t2); - [Pure] public bool Equals(TransitionTime other) => _isFixedDateRule == other._isFixedDateRule && _timeOfDay == other._timeOfDay && @@ -101,7 +98,6 @@ private static void ValidateTransitionTime(DateTime timeOfDay, int month, int we { throw new ArgumentOutOfRangeException(nameof(dayOfWeek), SR.ArgumentOutOfRange_DayOfWeek); } - Contract.EndContractBlock(); timeOfDay.GetDatePart(out int timeOfDayYear, out int timeOfDayMonth, out int timeOfDayDay); if (timeOfDayYear != 1 || timeOfDayMonth != 1 || timeOfDayDay != 1 || (timeOfDay.Ticks % TimeSpan.TicksPerMillisecond != 0)) @@ -131,7 +127,6 @@ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext contex { throw new ArgumentNullException(nameof(info)); } - Contract.EndContractBlock(); info.AddValue("TimeOfDay", _timeOfDay); // Do not rename (binary serialization) info.AddValue("Month", _month); // Do not rename (binary serialization) diff --git a/src/mscorlib/src/System/TimeZoneInfo.Unix.cs b/src/mscorlib/src/System/TimeZoneInfo.Unix.cs index 921b71cbf7d8..ba50616098e4 100644 --- a/src/mscorlib/src/System/TimeZoneInfo.Unix.cs +++ b/src/mscorlib/src/System/TimeZoneInfo.Unix.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Globalization; using System.IO; using System.Text; @@ -1417,7 +1416,6 @@ public TZifType(byte[] data, int index) { throw new ArgumentException(SR.Argument_TimeZoneInfoInvalidTZif, nameof(data)); } - Contract.EndContractBlock(); UtcOffset = new TimeSpan(0, 0, TZif_ToInt32(data, index + 00)); IsDst = (data[index + 4] != 0); AbbreviationIndex = data[index + 5]; @@ -1444,7 +1442,6 @@ public TZifHead(byte[] data, int index) { throw new ArgumentException("bad data", nameof(data)); } - Contract.EndContractBlock(); Magic = (uint)TZif_ToInt32(data, index + 00); diff --git a/src/mscorlib/src/System/TimeZoneInfo.cs b/src/mscorlib/src/System/TimeZoneInfo.cs index 8d61c98040ea..f9b5ce872ad9 100644 --- a/src/mscorlib/src/System/TimeZoneInfo.cs +++ b/src/mscorlib/src/System/TimeZoneInfo.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.Serialization; using System.Threading; @@ -168,7 +167,6 @@ public TimeSpan[] GetAmbiguousTimeOffsets(DateTimeOffset dateTimeOffset) { throw new ArgumentException(SR.Argument_DateTimeOffsetIsNotAmbiguous, nameof(dateTimeOffset)); } - Contract.EndContractBlock(); DateTime adjustedTime = ConvertTime(dateTimeOffset, this).DateTime; @@ -215,7 +213,6 @@ public TimeSpan[] GetAmbiguousTimeOffsets(DateTime dateTime) { throw new ArgumentException(SR.Argument_DateTimeIsNotAmbiguous, nameof(dateTime)); } - Contract.EndContractBlock(); DateTime adjustedTime; if (dateTime.Kind == DateTimeKind.Local) @@ -603,7 +600,6 @@ public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZone { throw new ArgumentNullException(nameof(destinationTimeZone)); } - Contract.EndContractBlock(); // calculate the destination time zone offset DateTime utcDateTime = dateTimeOffset.UtcDateTime; @@ -627,7 +623,6 @@ public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo destinationTi { throw new ArgumentNullException(nameof(destinationTimeZone)); } - Contract.EndContractBlock(); // Special case to give a way clearing the cache without exposing ClearCachedData() if (dateTime.Ticks == 0) @@ -662,7 +657,6 @@ private static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZo { throw new ArgumentNullException(nameof(destinationTimeZone)); } - Contract.EndContractBlock(); DateTimeKind sourceKind = cachedData.GetCorrespondingKind(sourceTimeZone); if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && (dateTime.Kind != DateTimeKind.Unspecified) && (dateTime.Kind != sourceKind)) @@ -788,7 +782,6 @@ public static TimeZoneInfo FromSerializedString(string source) { throw new ArgumentException(SR.Format(SR.Argument_InvalidSerializedString, source), nameof(source)); } - Contract.EndContractBlock(); return StringSerializer.GetDeserializedTimeZoneInfo(source); } @@ -847,7 +840,6 @@ public bool HasSameRules(TimeZoneInfo other) { throw new ArgumentNullException(nameof(other)); } - Contract.EndContractBlock(); // check the utcOffset and supportsDaylightSavingTime members if (_baseUtcOffset != other._baseUtcOffset || @@ -1039,7 +1031,6 @@ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext contex { throw new ArgumentNullException(nameof(info)); } - Contract.EndContractBlock(); info.AddValue("Id", _id); // Do not rename (binary serialization) info.AddValue("DisplayName", _displayName); // Do not rename (binary serialization) @@ -1929,7 +1920,6 @@ private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, bool /// /// Helper function that validates the TimeSpan is within +/- 14.0 hours /// - [Pure] internal static bool UtcOffsetOutOfRange(TimeSpan offset) => offset.TotalHours < -14.0 || offset.TotalHours > 14.0; @@ -1958,7 +1948,6 @@ private static void ValidateTimeZoneInfo(string id, TimeSpan baseUtcOffset, Adju { throw new ArgumentException(SR.Argument_TimeSpanHasSeconds, nameof(baseUtcOffset)); } - Contract.EndContractBlock(); adjustmentRulesSupportDst = false; diff --git a/src/mscorlib/src/System/Tuple.cs b/src/mscorlib/src/System/Tuple.cs index 6a8758278c2c..3381c750d032 100644 --- a/src/mscorlib/src/System/Tuple.cs +++ b/src/mscorlib/src/System/Tuple.cs @@ -7,7 +7,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; // diff --git a/src/mscorlib/src/System/Type.CoreCLR.cs b/src/mscorlib/src/System/Type.CoreCLR.cs index 23a96fa32fcd..571f53e473ea 100644 --- a/src/mscorlib/src/System/Type.CoreCLR.cs +++ b/src/mscorlib/src/System/Type.CoreCLR.cs @@ -4,7 +4,6 @@ using System.Reflection; using System.Runtime.CompilerServices; -using System.Diagnostics.Contracts; using StackCrawlMark = System.Threading.StackCrawlMark; namespace System @@ -111,7 +110,6 @@ internal virtual RuntimeTypeHandle GetTypeHandleInternal() [MethodImpl(MethodImplOptions.InternalCall)] internal static extern RuntimeType GetTypeFromHandleUnsafe(IntPtr handle); - [Pure] [MethodImpl(MethodImplOptions.InternalCall)] public static extern Type GetTypeFromHandle(RuntimeTypeHandle handle); @@ -121,13 +119,11 @@ internal virtual RuntimeTypeHandle GetTypeHandleInternal() #if FEATURE_COMINTEROP internal bool IsWindowsRuntimeObject { - [Pure] get { return IsWindowsRuntimeObjectImpl(); } } internal bool IsExportedToWindowsRuntime { - [Pure] get { return IsExportedToWindowsRuntimeImpl(); } } @@ -156,11 +152,9 @@ internal virtual string FormatTypeName(bool serialization) throw new NotImplementedException(); } - [Pure] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern bool operator ==(Type left, Type right); - [Pure] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern bool operator !=(Type left, Type right); diff --git a/src/mscorlib/src/System/TypeLoadException.cs b/src/mscorlib/src/System/TypeLoadException.cs index 840d97702b7f..90541dafef40 100644 --- a/src/mscorlib/src/System/TypeLoadException.cs +++ b/src/mscorlib/src/System/TypeLoadException.cs @@ -18,7 +18,6 @@ using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; -using System.Diagnostics.Contracts; namespace System { diff --git a/src/mscorlib/src/System/TypeNameParser.cs b/src/mscorlib/src/System/TypeNameParser.cs index 58bbe6f0922b..9bd772e574cd 100644 --- a/src/mscorlib/src/System/TypeNameParser.cs +++ b/src/mscorlib/src/System/TypeNameParser.cs @@ -4,7 +4,6 @@ using System; using System.Diagnostics; -using System.Diagnostics.Contracts; using System.IO; using System.Reflection; using System.Security; @@ -75,7 +74,6 @@ internal static Type GetType( throw new ArgumentNullException(nameof(typeName)); if (typeName.Length > 0 && typeName[0] == '\0') throw new ArgumentException(SR.Format_StringZeroLength); - Contract.EndContractBlock(); Type ret = null; @@ -192,7 +190,7 @@ private unsafe Type ConstructType( private static Assembly ResolveAssembly(string asmName, Func assemblyResolver, bool throwOnError, ref StackCrawlMark stackMark) { - Contract.Requires(asmName != null && asmName.Length > 0); + Debug.Assert(asmName != null && asmName.Length > 0); Assembly assembly = null; @@ -230,7 +228,7 @@ private static Assembly ResolveAssembly(string asmName, Func typeResolver, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) { - Contract.Requires(names != null && names.Length > 0); + Debug.Assert(names != null && names.Length > 0); Type type = null; diff --git a/src/mscorlib/src/System/TypedReference.cs b/src/mscorlib/src/System/TypedReference.cs index ca65082158e3..e29e8808dd6d 100644 --- a/src/mscorlib/src/System/TypedReference.cs +++ b/src/mscorlib/src/System/TypedReference.cs @@ -13,7 +13,6 @@ namespace System using CultureInfo = System.Globalization.CultureInfo; using FieldInfo = System.Reflection.FieldInfo; using System.Runtime.Versioning; - using System.Diagnostics.Contracts; [CLSCompliant(false)] [System.Runtime.Versioning.NonVersionable] // This only applies to field layout @@ -29,7 +28,6 @@ public static TypedReference MakeTypedReference(Object target, FieldInfo[] flds) throw new ArgumentNullException(nameof(target)); if (flds == null) throw new ArgumentNullException(nameof(flds)); - Contract.EndContractBlock(); if (flds.Length == 0) throw new ArgumentException(SR.Arg_ArrayZeroError); diff --git a/src/mscorlib/src/System/UIntPtr.cs b/src/mscorlib/src/System/UIntPtr.cs index 1bed651e6fb3..d0fe263a3268 100644 --- a/src/mscorlib/src/System/UIntPtr.cs +++ b/src/mscorlib/src/System/UIntPtr.cs @@ -17,7 +17,6 @@ namespace System using System.Globalization; using System.Runtime.Serialization; using System.Security; - using System.Diagnostics.Contracts; [Serializable] [CLSCompliant(false)] @@ -70,7 +69,6 @@ unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext { throw new ArgumentNullException(nameof(info)); } - Contract.EndContractBlock(); info.AddValue("value", (ulong)_value); } @@ -116,8 +114,6 @@ public unsafe ulong ToUInt64() public unsafe override String ToString() { - Contract.Ensures(Contract.Result() != null); - #if BIT64 return ((ulong)_value).ToString(CultureInfo.InvariantCulture); #else // 32 diff --git a/src/mscorlib/src/System/Variant.cs b/src/mscorlib/src/System/Variant.cs index b468ab2f980b..7717fc485fff 100644 --- a/src/mscorlib/src/System/Variant.cs +++ b/src/mscorlib/src/System/Variant.cs @@ -19,7 +19,6 @@ using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System { diff --git a/src/mscorlib/src/System/WeakReference.cs b/src/mscorlib/src/System/WeakReference.cs index a6a30c197805..bde7586590b4 100644 --- a/src/mscorlib/src/System/WeakReference.cs +++ b/src/mscorlib/src/System/WeakReference.cs @@ -15,7 +15,6 @@ using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Diagnostics; -using System.Diagnostics.Contracts; namespace System { @@ -56,7 +55,6 @@ protected WeakReference(SerializationInfo info, StreamingContext context) { throw new ArgumentNullException(nameof(info)); } - Contract.EndContractBlock(); Object target = info.GetValue("TrackedObject", typeof(Object)); // Do not rename (binary serialization) bool trackResurrection = info.GetBoolean("TrackResurrection"); // Do not rename (binary serialization) @@ -108,7 +106,6 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte { throw new ArgumentNullException(nameof(info)); } - Contract.EndContractBlock(); info.AddValue("TrackedObject", Target, typeof(Object)); // Do not rename (binary serialization) info.AddValue("TrackResurrection", IsTrackResurrection()); // Do not rename (binary serialization) } diff --git a/src/mscorlib/src/System/WeakReferenceOfT.cs b/src/mscorlib/src/System/WeakReferenceOfT.cs index 7347683e2f05..15f6daf07a4d 100644 --- a/src/mscorlib/src/System/WeakReferenceOfT.cs +++ b/src/mscorlib/src/System/WeakReferenceOfT.cs @@ -15,7 +15,6 @@ using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.Versioning; -using System.Diagnostics.Contracts; namespace System { @@ -51,7 +50,6 @@ internal WeakReference(SerializationInfo info, StreamingContext context) { throw new ArgumentNullException(nameof(info)); } - Contract.EndContractBlock(); T target = (T)info.GetValue("TrackedObject", typeof(T)); // Do not rename (binary serialization) bool trackResurrection = info.GetBoolean("TrackResurrection"); // Do not rename (binary serialization) @@ -104,7 +102,6 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new ArgumentNullException(nameof(info)); } - Contract.EndContractBlock(); info.AddValue("TrackedObject", this.Target, typeof(T)); // Do not rename (binary serialization) info.AddValue("TrackResurrection", IsTrackResurrection()); // Do not rename (binary serialization)