**
===========================================================*/
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
[Pure]
public override String ToString()
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
[Pure]
public String ToString(String format)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
[Pure]
public String ToString(IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
[Pure]
public String ToString(String format, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
}
[Pure]
public override String ToString()
{
- Contract.Ensures(Contract.Result<String>() != null);
return Char.ToString(m_value);
}
[Pure]
public String ToString(IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Char.ToString(m_value);
}
{
throw new ArgumentNullException(nameof(s));
}
- Contract.EndContractBlock();
if (s.Length != 1)
{
{
if (culture == null)
throw new ArgumentNullException(nameof(culture));
- Contract.EndContractBlock();
return culture.TextInfo.ToUpper(c);
}
{
if (culture == null)
throw new ArgumentNullException(nameof(culture));
- Contract.EndContractBlock();
return culture.TextInfo.ToLower(c);
}
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- Contract.EndContractBlock();
return (IsSurrogate(s[index]));
}
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- Contract.EndContractBlock();
if (IsLatin1(s[index]))
{
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- Contract.EndContractBlock();
if (IsLatin1(s[index]))
{
return (GetLatin1UnicodeCategory(s[index]));
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- Contract.EndContractBlock();
return CharUnicodeInfo.GetNumericValue(s, index);
}
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- Contract.EndContractBlock();
return (IsHighSurrogate(s[index]));
}
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- Contract.EndContractBlock();
return (IsLowSurrogate(s[index]));
}
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- Contract.EndContractBlock();
if (index + 1 < s.Length)
{
return (IsSurrogatePair(s[index], s[index + 1]));
{
throw new ArgumentOutOfRangeException(nameof(utf32), SR.ArgumentOutOfRange_InvalidUTF32);
}
- Contract.EndContractBlock();
if (utf32 < UNICODE_PLANE01_START)
{
{
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);
}
{
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)
using System;
using System.Runtime.CompilerServices;
-using System.Diagnostics.Contracts;
namespace System.Collections.Generic
{
// See the LICENSE file in the project root for more information.
using System;
-using System.Diagnostics.Contracts;
namespace System.Collections.Generic
{
using System.Collections;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
-using System.Diagnostics.Contracts;
namespace System.Collections.Generic
{
using System;
using System.Collections;
using System.Runtime.CompilerServices;
-using System.Diagnostics.Contracts;
namespace System.Collections.Generic
{
// 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
// See the LICENSE file in the project root for more information.
using System;
-using System.Diagnostics.Contracts;
namespace System.Collections.Generic
{
// 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
using System.Collections.ObjectModel;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
namespace System.Collections.Generic
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]
{
if (capacity < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
if (capacity == 0)
_items = s_emptyArray;
{
if (collection == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
- Contract.EndContractBlock();
ICollection<T> c = collection as ICollection<T>;
if (c != null)
{
get
{
- Contract.Ensures(Contract.Result<int>() >= 0);
return _items.Length;
}
set
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity);
}
- Contract.EndContractBlock();
if (value != _items.Length)
{
{
get
{
- Contract.Ensures(Contract.Result<int>() >= 0);
return _size;
}
}
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
- Contract.EndContractBlock();
return _items[index];
}
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
- Contract.EndContractBlock();
_items[index] = value;
_version++;
}
//
public void AddRange(IEnumerable<T> collection)
{
- Contract.Ensures(Count >= Contract.OldValue(Count));
-
InsertRange(_size, collection);
}
public ReadOnlyCollection<T> AsReadOnly()
{
- Contract.Ensures(Contract.Result<ReadOnlyCollection<T>>() != null);
return new ReadOnlyCollection<T>(this);
}
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
- Contract.Ensures(Contract.Result<int>() <= index + count);
- Contract.EndContractBlock();
return Array.BinarySearch<T>(_items, index, count, item, comparer);
}
public int BinarySearch(T item)
{
- Contract.Ensures(Contract.Result<int>() <= Count);
return BinarySearch(0, Count, item, null);
}
public int BinarySearch(T item, IComparer<T> comparer)
{
- Contract.Ensures(Contract.Result<int>() <= Count);
return BinarySearch(0, Count, item, comparer);
}
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter);
}
- Contract.EndContractBlock();
List<TOutput> list = new List<TOutput>(_size);
for (int i = 0; i < _size; i++)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
- Contract.EndContractBlock();
try
{
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
}
- Contract.EndContractBlock();
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, index, array, arrayIndex, count);
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
- Contract.EndContractBlock();
for (int i = 0; i < _size; i++)
{
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
- Contract.EndContractBlock();
List<T> list = new List<T>();
for (int i = 0; i < _size; i++)
public int FindIndex(Predicate<T> match)
{
- Contract.Ensures(Contract.Result<int>() >= -1);
- Contract.Ensures(Contract.Result<int>() < Count);
return FindIndex(0, _size, match);
}
public int FindIndex(int startIndex, Predicate<T> match)
{
- Contract.Ensures(Contract.Result<int>() >= -1);
- Contract.Ensures(Contract.Result<int>() < startIndex + Count);
return FindIndex(startIndex, _size - startIndex, match);
}
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
- Contract.Ensures(Contract.Result<int>() >= -1);
- Contract.Ensures(Contract.Result<int>() < startIndex + count);
- Contract.EndContractBlock();
int endIndex = startIndex + count;
for (int i = startIndex; i < endIndex; i++)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
- Contract.EndContractBlock();
for (int i = _size - 1; i >= 0; i--)
{
public int FindLastIndex(Predicate<T> match)
{
- Contract.Ensures(Contract.Result<int>() >= -1);
- Contract.Ensures(Contract.Result<int>() < Count);
return FindLastIndex(_size - 1, _size, match);
}
public int FindLastIndex(int startIndex, Predicate<T> match)
{
- Contract.Ensures(Contract.Result<int>() >= -1);
- Contract.Ensures(Contract.Result<int>() <= startIndex);
return FindLastIndex(startIndex, startIndex + 1, match);
}
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
- Contract.Ensures(Contract.Result<int>() >= -1);
- Contract.Ensures(Contract.Result<int>() <= startIndex);
- Contract.EndContractBlock();
if (_size == 0)
{
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action);
}
- Contract.EndContractBlock();
int version = _version;
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
}
- Contract.Ensures(Contract.Result<List<T>>() != null);
- Contract.EndContractBlock();
List<T> list = new List<T>(count);
Array.Copy(_items, index, list._items, 0, count);
//
public int IndexOf(T item)
{
- Contract.Ensures(Contract.Result<int>() >= -1);
- Contract.Ensures(Contract.Result<int>() < Count);
return Array.IndexOf(_items, item, 0, _size);
}
{
if (index > _size)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
- Contract.Ensures(Contract.Result<int>() >= -1);
- Contract.Ensures(Contract.Result<int>() < Count);
- Contract.EndContractBlock();
return Array.IndexOf(_items, item, index, _size - index);
}
if (count < 0 || index > _size - count)
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
- Contract.Ensures(Contract.Result<int>() >= -1);
- Contract.Ensures(Contract.Result<int>() < Count);
- Contract.EndContractBlock();
return Array.IndexOf(_items, item, index, count);
}
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert);
}
- Contract.EndContractBlock();
if (_size == _items.Length) EnsureCapacity(_size + 1);
if (index < _size)
{
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
- Contract.EndContractBlock();
ICollection<T> c = collection as ICollection<T>;
if (c != null)
//
public int LastIndexOf(T item)
{
- Contract.Ensures(Contract.Result<int>() >= -1);
- Contract.Ensures(Contract.Result<int>() < Count);
if (_size == 0)
{ // Special case for empty list
return -1;
{
if (index >= _size)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
- Contract.Ensures(Contract.Result<int>() >= -1);
- Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index)));
- Contract.EndContractBlock();
return LastIndexOf(item, index, index + 1);
}
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
- Contract.Ensures(Contract.Result<int>() >= -1);
- Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index)));
- Contract.EndContractBlock();
if (_size == 0)
{ // Special case for empty list
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(Count));
- Contract.EndContractBlock();
int freeIndex = 0; // the first free slot in items array
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
- Contract.EndContractBlock();
_size--;
if (index < _size)
{
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
- Contract.EndContractBlock();
if (count > 0)
{
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
- Contract.EndContractBlock();
if (count > 1)
{
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
- Contract.EndContractBlock();
if (count > 1)
{
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison);
}
- Contract.EndContractBlock();
if (_size > 1)
{
// This requires copying the List, which is an O(n) operation.
public T[] ToArray()
{
- Contract.Ensures(Contract.Result<T[]>() != null);
- Contract.Ensures(Contract.Result<T[]>().Length == Count);
-
if (_size == 0)
{
return s_emptyArray;
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
- Contract.EndContractBlock();
for (int i = 0; i < _size; i++)
{
// See the LICENSE file in the project root for more information.
using System;
-using System.Diagnostics.Contracts;
namespace System.Collections
{
// See the LICENSE file in the project root for more information.
using System;
-using System.Diagnostics.Contracts;
namespace System.Collections
{
// See the LICENSE file in the project root for more information.
using System;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
namespace System.Collections
{
// Returns an IEnumerator for this enumerable Object. The enumerator provides
// a simple way to access all the contents of a collection.
- [Pure]
IEnumerator GetEnumerator();
}
}
// See the LICENSE file in the project root for more information.
using System;
-using System.Diagnostics.Contracts;
namespace System.Collections
{
**
===========================================================*/
-using System.Diagnostics.Contracts;
namespace System.Collections
{
{
throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
- Contract.EndContractBlock();
DictionaryNode node = head;
while (node != null)
{
throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
- Contract.EndContractBlock();
version++;
{
throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
- Contract.EndContractBlock();
version++;
{
throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
- Contract.EndContractBlock();
for (DictionaryNode node = head; node != null; node = node.next)
{
if (node.key.Equals(key))
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)
{
{
throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
- Contract.EndContractBlock();
version++;
DictionaryNode last = null;
DictionaryNode node;
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)
using System.Runtime.Versioning;
using System.Security;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System
{
// 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;
// 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;
{
throw new ArgumentNullException(nameof(targetType));
}
- Contract.EndContractBlock();
if (ReferenceEquals(value.GetType(), targetType))
{
{
throw new ArgumentNullException(nameof(conversionType));
}
- Contract.EndContractBlock();
if (value == null)
{
public static char ToChar(sbyte value)
{
if (value < 0) ThrowCharOverflowException();
- Contract.EndContractBlock();
return (char)value;
}
public static char ToChar(short value)
{
if (value < 0) ThrowCharOverflowException();
- Contract.EndContractBlock();
return (char)value;
}
public static char ToChar(int value)
{
if (value < 0 || value > Char.MaxValue) ThrowCharOverflowException();
- Contract.EndContractBlock();
return (char)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;
}
public static char ToChar(ulong value)
{
if (value > Char.MaxValue) ThrowCharOverflowException();
- Contract.EndContractBlock();
return (char)value;
}
{
if (value == null)
throw new ArgumentNullException(nameof(value));
- Contract.EndContractBlock();
if (value.Length != 1)
throw new FormatException(SR.Format_NeedSingleChar);
public static sbyte ToSByte(char value)
{
if (value > SByte.MaxValue) ThrowSByteOverflowException();
- Contract.EndContractBlock();
return (sbyte)value;
}
public static sbyte ToSByte(byte value)
{
if (value > SByte.MaxValue) ThrowSByteOverflowException();
- Contract.EndContractBlock();
return (sbyte)value;
}
public static sbyte ToSByte(short value)
{
if (value < SByte.MinValue || value > SByte.MaxValue) ThrowSByteOverflowException();
- Contract.EndContractBlock();
return (sbyte)value;
}
public static sbyte ToSByte(ushort value)
{
if (value > SByte.MaxValue) ThrowSByteOverflowException();
- Contract.EndContractBlock();
return (sbyte)value;
}
public static sbyte ToSByte(int value)
{
if (value < SByte.MinValue || value > SByte.MaxValue) ThrowSByteOverflowException();
- Contract.EndContractBlock();
return (sbyte)value;
}
public static sbyte ToSByte(uint value)
{
if (value > SByte.MaxValue) ThrowSByteOverflowException();
- Contract.EndContractBlock();
return (sbyte)value;
}
public static sbyte ToSByte(long value)
{
if (value < SByte.MinValue || value > SByte.MaxValue) ThrowSByteOverflowException();
- Contract.EndContractBlock();
return (sbyte)value;
}
public static sbyte ToSByte(ulong value)
{
if (value > (ulong)SByte.MaxValue) ThrowSByteOverflowException();
- Contract.EndContractBlock();
return (sbyte)value;
}
public static byte ToByte(char value)
{
if (value > Byte.MaxValue) ThrowByteOverflowException();
- Contract.EndContractBlock();
return (byte)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;
}
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;
}
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;
}
public static byte ToByte(ulong value)
{
if (value > Byte.MaxValue) ThrowByteOverflowException();
- Contract.EndContractBlock();
return (byte)value;
}
public static short ToInt16(char value)
{
if (value > Int16.MaxValue) ThrowInt16OverflowException();
- Contract.EndContractBlock();
return (short)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;
}
public static short ToInt16(uint value)
{
if (value > Int16.MaxValue) ThrowInt16OverflowException();
- Contract.EndContractBlock();
return (short)value;
}
public static short ToInt16(long value)
{
if (value < Int16.MinValue || value > Int16.MaxValue) ThrowInt16OverflowException();
- Contract.EndContractBlock();
return (short)value;
}
public static short ToInt16(ulong value)
{
if (value > (ulong)Int16.MaxValue) ThrowInt16OverflowException();
- Contract.EndContractBlock();
return (short)value;
}
public static ushort ToUInt16(sbyte value)
{
if (value < 0) ThrowUInt16OverflowException();
- Contract.EndContractBlock();
return (ushort)value;
}
public static ushort ToUInt16(short value)
{
if (value < 0) ThrowUInt16OverflowException();
- Contract.EndContractBlock();
return (ushort)value;
}
public static ushort ToUInt16(int value)
{
if (value < 0 || value > UInt16.MaxValue) ThrowUInt16OverflowException();
- Contract.EndContractBlock();
return (ushort)value;
}
public static ushort ToUInt16(uint value)
{
if (value > UInt16.MaxValue) ThrowUInt16OverflowException();
- Contract.EndContractBlock();
return (ushort)value;
}
public static ushort ToUInt16(long value)
{
if (value < 0 || value > UInt16.MaxValue) ThrowUInt16OverflowException();
- Contract.EndContractBlock();
return (ushort)value;
}
public static ushort ToUInt16(ulong value)
{
if (value > UInt16.MaxValue) ThrowUInt16OverflowException();
- Contract.EndContractBlock();
return (ushort)value;
}
public static int ToInt32(uint value)
{
if (value > Int32.MaxValue) ThrowInt32OverflowException();
- Contract.EndContractBlock();
return (int)value;
}
public static int ToInt32(long value)
{
if (value < Int32.MinValue || value > Int32.MaxValue) ThrowInt32OverflowException();
- Contract.EndContractBlock();
return (int)value;
}
public static int ToInt32(ulong value)
{
if (value > Int32.MaxValue) ThrowInt32OverflowException();
- Contract.EndContractBlock();
return (int)value;
}
public static uint ToUInt32(sbyte value)
{
if (value < 0) ThrowUInt32OverflowException();
- Contract.EndContractBlock();
return (uint)value;
}
public static uint ToUInt32(short value)
{
if (value < 0) ThrowUInt32OverflowException();
- Contract.EndContractBlock();
return (uint)value;
}
public static uint ToUInt32(int value)
{
if (value < 0) ThrowUInt32OverflowException();
- Contract.EndContractBlock();
return (uint)value;
}
public static uint ToUInt32(long value)
{
if (value < 0 || value > UInt32.MaxValue) ThrowUInt32OverflowException();
- Contract.EndContractBlock();
return (uint)value;
}
public static uint ToUInt32(ulong value)
{
if (value > UInt32.MaxValue) ThrowUInt32OverflowException();
- Contract.EndContractBlock();
return (uint)value;
}
public static long ToInt64(ulong value)
{
if (value > Int64.MaxValue) ThrowInt64OverflowException();
- Contract.EndContractBlock();
return (long)value;
}
public static ulong ToUInt64(sbyte value)
{
if (value < 0) ThrowUInt64OverflowException();
- Contract.EndContractBlock();
return (ulong)value;
}
public static ulong ToUInt64(short value)
{
if (value < 0) ThrowUInt64OverflowException();
- Contract.EndContractBlock();
return (ulong)value;
}
public static ulong ToUInt64(int value)
{
if (value < 0) ThrowUInt64OverflowException();
- Contract.EndContractBlock();
return (ulong)value;
}
public static ulong ToUInt64(long value)
{
if (value < 0) ThrowUInt64OverflowException();
- Contract.EndContractBlock();
return (ulong)value;
}
public static string ToString(bool value)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString();
}
public static string ToString(bool value, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString();
}
public static string ToString(char value)
{
- Contract.Ensures(Contract.Result<string>() != null);
return Char.ToString(value);
}
public static string ToString(char value, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString();
}
[CLSCompliant(false)]
public static string ToString(sbyte value)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(CultureInfo.CurrentCulture);
}
[CLSCompliant(false)]
public static string ToString(sbyte value, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
public static string ToString(byte value)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(CultureInfo.CurrentCulture);
}
public static string ToString(byte value, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
public static string ToString(short value)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(CultureInfo.CurrentCulture);
}
public static string ToString(short value, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
[CLSCompliant(false)]
public static string ToString(ushort value)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(CultureInfo.CurrentCulture);
}
[CLSCompliant(false)]
public static string ToString(ushort value, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
public static string ToString(int value)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(CultureInfo.CurrentCulture);
}
public static string ToString(int value, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
[CLSCompliant(false)]
public static string ToString(uint value)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(CultureInfo.CurrentCulture);
}
[CLSCompliant(false)]
public static string ToString(uint value, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
public static string ToString(long value)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(CultureInfo.CurrentCulture);
}
public static string ToString(long value, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
[CLSCompliant(false)]
public static string ToString(ulong value)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(CultureInfo.CurrentCulture);
}
[CLSCompliant(false)]
public static string ToString(ulong value, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
public static string ToString(float value)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(CultureInfo.CurrentCulture);
}
public static string ToString(float value, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
public static string ToString(double value)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(CultureInfo.CurrentCulture);
}
public static string ToString(double value, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
public static string ToString(decimal value)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(CultureInfo.CurrentCulture);
}
public static string ToString(Decimal value, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
public static string ToString(DateTime value)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString();
}
public static string ToString(DateTime value, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
public static String ToString(String value)
{
- Contract.Ensures(Contract.Result<string>() == value); // We were always skipping the null check here.
return value;
}
public static String ToString(String value, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<string>() == value); // We were always skipping the null check here.
return value; // avoid the null check
}
{
throw new ArgumentException(SR.Arg_InvalidBase);
}
- Contract.EndContractBlock();
if (value == null)
{
{
throw new ArgumentException(SR.Arg_InvalidBase);
}
- Contract.EndContractBlock();
if (value == null)
{
{
throw new ArgumentException(SR.Arg_InvalidBase);
}
- Contract.EndContractBlock();
if (value == null)
{
{
throw new ArgumentException(SR.Arg_InvalidBase);
}
- Contract.EndContractBlock();
if (value == null)
{
{
throw new ArgumentException(SR.Arg_InvalidBase);
}
- Contract.EndContractBlock();
return value != null ?
ParseNumbers.StringToInt(value.AsReadOnlySpan(), fromBase, ParseNumbers.IsTight) :
0;
{
throw new ArgumentException(SR.Arg_InvalidBase);
}
- Contract.EndContractBlock();
return value != null ?
(uint)ParseNumbers.StringToInt(value.AsReadOnlySpan(), fromBase, ParseNumbers.TreatAsUnsigned | ParseNumbers.IsTight) :
0;
{
throw new ArgumentException(SR.Arg_InvalidBase);
}
- Contract.EndContractBlock();
return value != null ?
ParseNumbers.StringToLong(value.AsReadOnlySpan(), fromBase, ParseNumbers.IsTight) :
0;
{
throw new ArgumentException(SR.Arg_InvalidBase);
}
- Contract.EndContractBlock();
return value != null ?
(ulong)ParseNumbers.StringToLong(value.AsReadOnlySpan(), fromBase, ParseNumbers.TreatAsUnsigned | ParseNumbers.IsTight) :
0;
{
throw new ArgumentException(SR.Arg_InvalidBase);
}
- Contract.EndContractBlock();
return ParseNumbers.IntToString((int)value, toBase, -1, ' ', ParseNumbers.PrintAsI1);
}
{
throw new ArgumentException(SR.Arg_InvalidBase);
}
- Contract.EndContractBlock();
return ParseNumbers.IntToString((int)value, toBase, -1, ' ', ParseNumbers.PrintAsI2);
}
{
throw new ArgumentException(SR.Arg_InvalidBase);
}
- Contract.EndContractBlock();
return ParseNumbers.IntToString(value, toBase, -1, ' ', 0);
}
{
throw new ArgumentException(SR.Arg_InvalidBase);
}
- Contract.EndContractBlock();
return ParseNumbers.LongToString(value, toBase, -1, ' ', 0);
}
{
throw new ArgumentNullException(nameof(inArray));
}
- Contract.Ensures(Contract.Result<string>() != null);
- Contract.EndContractBlock();
return ToBase64String(inArray, 0, inArray.Length, Base64FormattingOptions.None);
}
{
throw new ArgumentNullException(nameof(inArray));
}
- Contract.Ensures(Contract.Result<string>() != null);
- Contract.EndContractBlock();
return ToBase64String(inArray, 0, inArray.Length, options);
}
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<string>() != null);
- Contract.EndContractBlock();
int inArrayLength;
int stringLength;
public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut)
{
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() <= outArray.Length);
- Contract.EndContractBlock();
-
return ToBase64CharArray(inArray, offsetIn, length, outArray, offsetOut, Base64FormattingOptions.None);
}
{
throw new ArgumentException(string.Format(SR.Arg_EnumIllegalVal, (int)options));
}
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() <= outArray.Length);
- Contract.EndContractBlock();
int retVal;
if (s == null)
throw new ArgumentNullException(nameof(s));
- Contract.EndContractBlock();
unsafe
{
if (offset > inArray.Length - length)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_OffsetLength);
- Contract.EndContractBlock();
if (inArray.Length == 0)
{
============================================================*/
using System;
-using System.Diagnostics.Contracts;
using System.Text;
using System.Collections;
using System.Globalization;
using System;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Threading;
using System.Globalization;
using System.Runtime;
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
{
if (ticks < MinTicks || ticks > MaxTicks)
throw new ArgumentOutOfRangeException(nameof(ticks), SR.ArgumentOutOfRange_DateTimeBadTicks);
- Contract.EndContractBlock();
_dateData = (UInt64)ticks;
}
{
throw new ArgumentException(SR.Argument_InvalidDateTimeKind, nameof(kind));
}
- Contract.EndContractBlock();
_dateData = ((UInt64)ticks | ((UInt64)kind << KindShift));
}
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));
}
{
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));
}
{
if (calendar == null)
throw new ArgumentNullException(nameof(calendar));
- Contract.EndContractBlock();
_dateData = (UInt64)calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks;
}
{
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)
{
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)
{
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)
{
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)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
Boolean foundTicks = false;
Boolean foundDateData = false;
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)
// parameter name out of the two for the exception.
throw new ArgumentOutOfRangeException("years", SR.ArgumentOutOfRange_DateTimeBadYears);
}
- Contract.EndContractBlock();
return AddMonths(value * 12);
}
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];
{
throw new ArgumentOutOfRangeException(nameof(fileTime), SR.ArgumentOutOfRange_FileTimeInvalid);
}
- Contract.EndContractBlock();
// This is the ticks in Universal time for this fileTime.
long universalTicks = fileTime + FileTimeOffset;
{
throw new ArgumentNullException(nameof(info));
}
- Contract.EndContractBlock();
// Serialize both the old and the new format
info.AddValue(TicksField, InternalTicks);
{
get
{
- Contract.Ensures(Contract.Result<int>() >= 1);
- Contract.Ensures(Contract.Result<int>() <= 31);
return GetDatePart(DatePartDay);
}
}
{
get
{
- Contract.Ensures(Contract.Result<DayOfWeek>() >= DayOfWeek.Sunday);
- Contract.Ensures(Contract.Result<DayOfWeek>() <= DayOfWeek.Saturday);
return (DayOfWeek)((InternalTicks / TicksPerDay + 1) % 7);
}
}
{
get
{
- Contract.Ensures(Contract.Result<int>() >= 1);
- Contract.Ensures(Contract.Result<int>() <= 366); // leap year
return GetDatePart(DatePartDayOfYear);
}
}
{
get
{
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() < 24);
return (int)((InternalTicks / TicksPerHour) % 24);
}
}
return (InternalKind == KindLocalAmbiguousDst);
}
- [Pure]
public DateTimeKind Kind
{
get
{
get
{
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() < 1000);
return (int)((InternalTicks / TicksPerMillisecond) % 1000);
}
}
{
get
{
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() < 60);
return (int)((InternalTicks / TicksPerMinute) % 60);
}
}
{
get
{
- Contract.Ensures(Contract.Result<int>() >= 1);
return GetDatePart(DatePartMonth);
}
}
{
get
{
- Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Local);
-
DateTime utc = UtcNow;
Boolean isAmbiguousLocalDst = false;
Int64 offset = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utc, out isAmbiguousLocalDst).Ticks;
{
get
{
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() < 60);
return (int)((InternalTicks / TicksPerSecond) % 60);
}
}
{
get
{
- Contract.Ensures(Contract.Result<int>() >= 1 && Contract.Result<int>() <= 9999);
return GetDatePart(DatePartYear);
}
}
{
throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_Year);
}
- Contract.EndContractBlock();
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
public String ToLongDateString()
{
- Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(this, "D", DateTimeFormatInfo.CurrentInfo);
}
public String ToLongTimeString()
{
- Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(this, "T", DateTimeFormatInfo.CurrentInfo);
}
public String ToShortDateString()
{
- Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(this, "d", DateTimeFormatInfo.CurrentInfo);
}
public String ToShortTimeString()
{
- Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(this, "t", DateTimeFormatInfo.CurrentInfo);
}
public override String ToString()
{
- Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(this, null, DateTimeFormatInfo.CurrentInfo);
}
public String ToString(String format)
{
- Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(this, format, DateTimeFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(this, null, DateTimeFormatInfo.GetInstance(provider));
}
public String ToString(String format, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(this, format, DateTimeFormatInfo.GetInstance(provider));
}
// time strings for the current instance of DateTime.
public String[] GetDateTimeFormats()
{
- Contract.Ensures(Contract.Result<String[]>() != null);
return (GetDateTimeFormats(CultureInfo.CurrentCulture));
}
// time strings for the current instance of DateTime.
public String[] GetDateTimeFormats(IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String[]>() != null);
return (DateTimeFormat.GetAllDateTimes(this, DateTimeFormatInfo.GetInstance(provider)));
}
// time strings for the current instance of DateTime.
public String[] GetDateTimeFormats(char format)
{
- Contract.Ensures(Contract.Result<String[]>() != null);
return (GetDateTimeFormats(format, CultureInfo.CurrentCulture));
}
// time strings for the current instance of DateTime.
public String[] GetDateTimeFormats(char format, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String[]>() != null);
return (DateTimeFormat.GetAllDateTimes(this, format, DateTimeFormatInfo.GetInstance(provider)));
}
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
/// </summary>
internal class ActivityTracker
{
-
/// <summary>
/// Called on work item begins. The activity name = providerName + activityName without 'Start' suffix.
/// It updates CurrentActivityId to track.
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
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
if ((level <= m_level) ||
(m_level == 0))
{
-
//
// Check if Keyword is enabled
//
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
/// </remarks>
public partial class EventSource : IDisposable
{
-
#if FEATURE_EVENTSOURCE_XPLAT
private static readonly EventListener persistent_Xplat_Listener = XplatEventLogger.InitializePersistentListener();
#endif //FEATURE_EVENTSOURCE_XPLAT
{
if (eventSourceType == null)
throw new ArgumentNullException(nameof(eventSourceType));
- Contract.EndContractBlock();
EventSourceAttribute attrib = (EventSourceAttribute)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute));
string name = eventSourceType.Name;
{
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);
#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;
{
if (eventSourceType == null)
throw new ArgumentNullException(nameof(eventSourceType));
- Contract.EndContractBlock();
EventSourceAttribute attrib = (EventSourceAttribute)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute), flags);
if (attrib != null && attrib.Name != null)
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;
{
throw new ArgumentNullException(nameof(eventSource));
}
- Contract.EndContractBlock();
eventSource.SendCommand(this, 0, 0, EventCommand.Update, true, level, matchAnyKeyword, arguments);
}
{
throw new ArgumentNullException(nameof(eventSource));
}
- Contract.EndContractBlock();
eventSource.SendCommand(this, 0, 0, EventCommand.Update, false, EventLevel.LogAlways, EventKeywords.None, null);
}
// do the lazy init if you know it is contract based (EventID >= 0)
if (EventId >= 0 && m_payloadNames == null)
{
-
var names = new List<string>();
foreach (var parameter in m_eventSource.m_eventData[EventId].Parameters)
{
private string CreateManifestString()
{
-
#if FEATURE_MANAGED_ETW_CHANNELS
// Write out the channels
if (channelTab != null)
// Write out the tasks
if (taskTab != null)
{
-
sb.Append(" <tasks>").AppendLine();
var sortedTasks = new List<int>(taskTab.Keys);
sortedTasks.Sort();
#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;
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
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
{
if (eventSource == null)
throw new ArgumentNullException(nameof(eventSource));
- Contract.EndContractBlock();
this.eventSource = eventSource;
}
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
{
/// <summary>
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
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
{
throw new ArgumentNullException(nameof(eventSourceName));
}
- Contract.EndContractBlock();
}
/// <summary>
throw new ArgumentNullException(nameof(eventName));
}
- Contract.EndContractBlock();
if (!this.IsEnabled())
{
throw new ArgumentNullException(nameof(eventName));
}
- Contract.EndContractBlock();
if (!this.IsEnabled())
{
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
throw new ArgumentNullException(nameof(name));
}
- Contract.EndContractBlock();
this.typeInfos = MakeArray(paramInfos);
this.name = name;
throw new ArgumentNullException(nameof(defaultName));
}
- Contract.EndContractBlock();
this.typeInfos = typeInfos;
this.name = defaultName;
throw new ArgumentNullException(nameof(paramInfos));
}
- Contract.EndContractBlock();
var recursionCheck = new List<Type>(paramInfos.Length);
var result = new TraceLoggingTypeInfo[paramInfos.Length];
throw new ArgumentNullException(nameof(types));
}
- Contract.EndContractBlock();
var recursionCheck = new List<Type>(types.Length);
var result = new TraceLoggingTypeInfo[types.Length];
throw new ArgumentNullException(nameof(typeInfos));
}
- Contract.EndContractBlock();
return (TraceLoggingTypeInfo[])typeInfos.Clone(); ;
}
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
throw new ArgumentNullException(nameof(dataType));
}
- Contract.EndContractBlock();
this.name = dataType.Name;
this.dataType = dataType;
throw new ArgumentNullException(nameof(name));
}
- Contract.EndContractBlock();
Statics.CheckName(name);
**
===========================================================*/
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
internal const double NegativeZero = -0.0;
/// <summary>Determines whether the specified value is finite (zero, subnormal, or normal).</summary>
- [Pure]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsFinite(double d)
}
/// <summary>Determines whether the specified value is infinite.</summary>
- [Pure]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsInfinity(double d)
}
/// <summary>Determines whether the specified value is NaN.</summary>
- [Pure]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsNaN(double d)
}
/// <summary>Determines whether the specified value is negative.</summary>
- [Pure]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsNegative(double d)
}
/// <summary>Determines whether the specified value is negative infinity.</summary>
- [Pure]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsNegativeInfinity(double d)
}
/// <summary>Determines whether the specified value is normal.</summary>
- [Pure]
[NonVersionable]
// This is probably not worth inlining, it has branches and should be rarely called
public unsafe static bool IsNormal(double d)
}
/// <summary>Determines whether the specified value is positive infinity.</summary>
- [Pure]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsPositiveInfinity(double d)
}
/// <summary>Determines whether the specified value is subnormal.</summary>
- [Pure]
[NonVersionable]
// This is probably not worth inlining, it has branches and should be rarely called
public unsafe static bool IsSubnormal(double d)
public override String ToString()
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDouble(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDouble(m_value, format, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDouble(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDouble(m_value, format, NumberFormatInfo.GetInstance(provider));
}
// 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
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());
String.Format(CultureInfo.InvariantCulture, SR.Format(SR.Argument_ResultCalendarRange,
minValue, maxValue)));
}
- Contract.EndContractBlock();
}
internal DateTime Add(DateTime time, double value, int scale)
nameof(firstDayOfWeek), SR.Format(SR.ArgumentOutOfRange_Range,
DayOfWeek.Sunday, DayOfWeek.Saturday));
}
- Contract.EndContractBlock();
switch (rule)
{
case CalendarWeekRule.FirstDay:
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
- Contract.EndContractBlock();
if (year < 100)
{
return ((TwoDigitYearMax / 100 - (year > TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year);
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
// 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
{
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR));
}
- Contract.EndContractBlock();
return s_yinfo[lunarYear - MIN_LUNISOLAR_YEAR, index];
}
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR));
}
- Contract.EndContractBlock();
return year;
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Text;
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;
internal static String[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi)
{
- Contract.Requires(dtfi != null);
+ Debug.Assert(dtfi != null);
String[] allFormats = null;
String[] results = null;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Globalization
{
get
{
- Contract.Ensures(Contract.Result<DateTimeFormatInfo>() != null);
if (s_invariantInfo == null)
{
DateTimeFormatInfo info = new DateTimeFormatInfo();
{
get
{
- Contract.Ensures(Contract.Result<DateTimeFormatInfo>() != null);
System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CurrentCulture;
if (!culture._isInherited)
{
throw new ArgumentNullException(nameof(value),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
ClearTokenHashTable();
amDesignator = value;
}
{
get
{
- Contract.Ensures(Contract.Result<Calendar>() != null);
-
Debug.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null");
return (this.calendar);
}
{
throw new ArgumentNullException(nameof(value), SR.ArgumentNull_Obj);
}
- Contract.EndContractBlock();
if (value == calendar)
{
return;
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
{
throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
ClearTokenHashTable();
dateSeparator = value;
}
throw new ArgumentNullException(nameof(value),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
fullDateTimePattern = value;
}
}
throw new ArgumentNullException(nameof(value),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
// Remember the new string
this.longDatePattern = value;
throw new ArgumentNullException(nameof(value),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
// Remember the new string
this.longTimePattern = value;
throw new ArgumentNullException(nameof(value),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
this.monthDayPattern = value;
}
throw new ArgumentNullException(nameof(value),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
ClearTokenHashTable();
pmDesignator = value;
if (value == null)
throw new ArgumentNullException(nameof(value),
SR.ArgumentNull_String);
- Contract.EndContractBlock();
// Remember the new string
this.shortDatePattern = value;
throw new ArgumentNullException(nameof(value),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
// Remember the new string
this.shortTimePattern = value;
throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
ClearTokenHashTable();
timeSeparator = value;
throw new ArgumentNullException(nameof(value),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
// Remember the new string
this.yearMonthPattern = value;
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 7), nameof(value));
}
- Contract.EndContractBlock();
CheckNullValue(value, value.Length);
ClearTokenHashTable();
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 7), nameof(value));
}
- Contract.EndContractBlock();
CheckNullValue(value, value.Length);
this.m_superShortDayNames = value;
}
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 7), nameof(value));
}
- Contract.EndContractBlock();
CheckNullValue(value, value.Length);
ClearTokenHashTable();
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 13), nameof(value));
}
- Contract.EndContractBlock();
CheckNullValue(value, value.Length - 1);
ClearTokenHashTable();
abbreviatedMonthNames = value;
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 13), nameof(value));
}
- Contract.EndContractBlock();
CheckNullValue(value, value.Length - 1);
monthNames = value;
ClearTokenHashTable();
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.
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.
public string[] GetAllDateTimePatterns(char format)
{
- Contract.Ensures(Contract.Result<String[]>() != null);
String[] result = null;
switch (format)
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]);
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]);
}
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]);
}
throw new ArgumentNullException(nameof(dtfi),
SR.ArgumentNull_Obj);
}
- Contract.EndContractBlock();
if (dtfi.IsReadOnly)
{
return (dtfi);
throw new ArgumentException(SR.Arg_ArrayZeroError, nameof(patterns));
}
- Contract.EndContractBlock();
for (int i = 0; i < patterns.Length; i++)
{
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 13), nameof(value));
}
- Contract.EndContractBlock();
CheckNullValue(value, value.Length - 1);
ClearTokenHashTable();
this.m_genitiveAbbreviatedMonthNames = value;
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 13), nameof(value));
}
- Contract.EndContractBlock();
CheckNullValue(value, value.Length - 1);
genitiveMonthNames = value;
ClearTokenHashTable();
{
throw new ArgumentException(SR.Argument_ConflictingDateTimeStyles, parameterName);
}
- Contract.EndContractBlock();
if (((style & DateTimeStyles.RoundtripKind) != 0)
&& ((style & (DateTimeStyles.AssumeLocal | DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)) != 0))
{
namespace System.Globalization
{
-
#if CORECLR
using StringStringDictionary = Dictionary<string, string>;
using StringList = List<string>;
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Text;
// COMPlus_LogToConsole=1
// COMPlus_LogLevel=9
// COMPlus_ManagedLogFacility=0x00001000
- [Pure]
[Conditional("_LOGGING")]
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)
{
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)
{
BCLDebug.Trace("DATETIME", "[DATETIME] TryParse return {0}, DS.{1}", message, dps);
#endif // _LOGGING
}
- [Pure]
[Conditional("_LOGGING")]
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)
{
buffer.Append(s);
return buffer.ToString();
}
- [Pure]
// return a string in the form: "Sun"
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)
{
// 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
{
nameof(sexagenaryYear),
SR.Format(SR.ArgumentOutOfRange_Range, 1, 60));
}
- Contract.EndContractBlock();
return ((sexagenaryYear - 1) % 10) + 1;
}
nameof(sexagenaryYear),
SR.Format(SR.ArgumentOutOfRange_Range, 1, 60));
}
- Contract.EndContractBlock();
return ((sexagenaryYear - 1) % 12) + 1;
}
String.Format(CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange,
MinSupportedDateTime, MaxSupportedDateTime));
}
- Contract.EndContractBlock();
}
internal void CheckEraRange(int era)
nameof(months),
SR.Format(SR.ArgumentOutOfRange_Range, -120000, 120000));
}
- Contract.EndContractBlock();
CheckTicksRange(time.Ticks);
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
- Contract.EndContractBlock();
year = base.ToFourDigitYear(year);
CheckYearRange(year, CurrentEra);
using System;
using System.Globalization;
-using System.Diagnostics.Contracts;
using System.Threading;
namespace System.Globalization
SR.Format(SR.ArgumentOutOfRange_Range,
GregorianCalendarTypes.Localized, GregorianCalendarTypes.TransliteratedFrench));
}
- Contract.EndContractBlock();
this.m_type = type;
}
-120000,
120000));
}
- Contract.EndContractBlock();
time.GetDatePart(out int y, out int m, out int d);
int i = m - 1 + months;
if (i >= 0)
throw new ArgumentOutOfRangeException(nameof(month), SR.Format(SR.ArgumentOutOfRange_Range,
1, 12));
}
- Contract.EndContractBlock();
if (era != CurrentEra && era != ADEra)
{
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range, 1, MaxYear));
}
- Contract.EndContractBlock();
return (0);
}
throw new ArgumentOutOfRangeException(nameof(month), SR.Format(SR.ArgumentOutOfRange_Range,
1, 12));
}
- Contract.EndContractBlock();
return (false);
}
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
- Contract.EndContractBlock();
if (year > MaxYear)
{
// See the LICENSE file in the project root for more information.
using System;
-using System.Diagnostics.Contracts;
using System.Threading;
namespace System.Globalization
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
- Contract.EndContractBlock();
if (era == Calendar.CurrentEra)
{
m_Cal.MinSupportedDateTime,
m_Cal.MaxSupportedDateTime));
}
- Contract.EndContractBlock();
}
// Returns the DateTime resulting from adding the given number of
-120000,
120000));
}
- Contract.EndContractBlock();
CheckTicksRange(time.Ticks);
int y = GetDatePart(time.Ticks, DatePartYear);
// 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)
{
//
1,
GetDaysInMonth(year, month, era)));
}
- Contract.EndContractBlock();
if (!IsLeapYear(year, era))
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedPosNum);
}
- Contract.EndContractBlock();
if (year < 100)
{
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Globalization
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
- Contract.EndContractBlock();
if (year < 100)
{
// 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
{
MinAdvancedHijri,
MaxAdvancedHijri));
}
- Contract.EndContractBlock();
VerifyWritable();
_hijriAdvance = value;
-120000,
120000));
}
- Contract.EndContractBlock();
// Get the date in Hijri calendar.
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
// 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);
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
- Contract.EndContractBlock();
if (year < 100)
{
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
namespace System.Globalization
{
}
- [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));
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedPosNum);
}
- Contract.EndContractBlock();
if (year > helper.MaxYear)
{
// 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
{
MIN_LUNISOLAR_YEAR,
MAX_LUNISOLAR_YEAR));
}
- Contract.EndContractBlock();
return s_yinfo[lunarYear - MIN_LUNISOLAR_YEAR, index];
}
// 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
{
-120000,
120000));
}
- Contract.EndContractBlock();
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
- Contract.EndContractBlock();
if (year > MaxYear)
{
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
namespace System.Globalization
{
}
- [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));
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
- Contract.EndContractBlock();
return (helper.ToFourDigitYear(year, this.TwoDigitYearMax));
}
// 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
{
MIN_LUNISOLAR_YEAR,
MAX_LUNISOLAR_YEAR));
}
- Contract.EndContractBlock();
return s_yinfo[lunarYear - MIN_LUNISOLAR_YEAR, index];
}
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR));
}
- Contract.EndContractBlock();
return year;
}
// 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.
// See the LICENSE file in the project root for more information.
using System;
-using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
using System.Text;
{
throw new ArgumentException(SR.Argument_EmptyDecString);
}
- Contract.EndContractBlock();
}
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)
{
throw new ArgumentException(SR.Argument_InvalidNativeDigitCount, propertyName);
}
- Contract.EndContractBlock();
for (int i = 0; i < nativeDig.Length; i++)
{
}
}
- [Pure]
private void VerifyWritable()
{
if (isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
- Contract.EndContractBlock();
}
// Returns a default NumberFormatInfo that will be universally
0,
99));
}
- Contract.EndContractBlock();
VerifyWritable();
currencyDecimalDigits = value;
}
throw new ArgumentNullException(nameof(CurrencyGroupSizes),
SR.ArgumentNull_Obj);
}
- Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
throw new ArgumentNullException(nameof(NumberGroupSizes),
SR.ArgumentNull_Obj);
}
- Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
throw new ArgumentNullException(nameof(PercentGroupSizes),
SR.ArgumentNull_Obj);
}
- Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize(nameof(PercentGroupSizes), inputSizes);
throw new ArgumentNullException(nameof(CurrencySymbol),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
VerifyWritable();
currencySymbol = value;
}
throw new ArgumentNullException(nameof(NaNSymbol),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
VerifyWritable();
nanSymbol = value;
}
0,
15));
}
- Contract.EndContractBlock();
VerifyWritable();
currencyNegativePattern = value;
}
0,
4));
}
- Contract.EndContractBlock();
VerifyWritable();
numberNegativePattern = value;
}
0,
3));
}
- Contract.EndContractBlock();
VerifyWritable();
percentPositivePattern = value;
}
0,
11));
}
- Contract.EndContractBlock();
VerifyWritable();
percentNegativePattern = value;
}
throw new ArgumentNullException(nameof(NegativeInfinitySymbol),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
VerifyWritable();
negativeInfinitySymbol = value;
}
throw new ArgumentNullException(nameof(NegativeSign),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
VerifyWritable();
negativeSign = value;
}
0,
99));
}
- Contract.EndContractBlock();
VerifyWritable();
numberDecimalDigits = value;
}
0,
3));
}
- Contract.EndContractBlock();
VerifyWritable();
currencyPositivePattern = value;
}
throw new ArgumentNullException(nameof(PositiveInfinitySymbol),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
VerifyWritable();
positiveInfinitySymbol = value;
}
throw new ArgumentNullException(nameof(PositiveSign),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
VerifyWritable();
positiveSign = value;
}
0,
99));
}
- Contract.EndContractBlock();
VerifyWritable();
percentDecimalDigits = value;
}
throw new ArgumentNullException(nameof(PercentSymbol),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
VerifyWritable();
percentSymbol = value;
}
throw new ArgumentNullException(nameof(PerMilleSymbol),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
VerifyWritable();
perMilleSymbol = value;
}
{
throw new ArgumentNullException(nameof(nfi));
}
- Contract.EndContractBlock();
if (nfi.IsReadOnly)
{
return (nfi);
{
throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style));
}
- Contract.EndContractBlock();
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // Check for hex number
if ((style & ~NumberStyles.HexNumber) != 0)
{
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);
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Globalization
{
-120000,
120000));
}
- Contract.EndContractBlock();
// Get the date in Persian calendar.
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
- Contract.EndContractBlock();
if (year < 100)
{
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Globalization
{
{
throw new ArgumentNullException((sortkey1 == null ? nameof(sortkey1) : nameof(sortkey2)));
}
- Contract.EndContractBlock();
byte[] key1Data = sortkey1._keyData;
byte[] key2Data = sortkey2._keyData;
using System;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Globalization
throw new ArgumentNullException(nameof(String),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
_str = value;
_indexes = null;
{
throw new ArgumentNullException(nameof(str));
}
- Contract.EndContractBlock();
int len = str.Length;
if (index < 0 || index >= len)
{
throw new ArgumentNullException(nameof(str));
}
- Contract.EndContractBlock();
int len = str.Length;
if (index < 0 || (index > len))
{
throw new ArgumentNullException(nameof(str));
}
- Contract.EndContractBlock();
int len = str.Length;
int[] result = new int[len];
using System;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
namespace System.Globalization
{
}
- [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));
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedPosNum);
}
- Contract.EndContractBlock();
if (year > helper.MaxYear)
{
// See the LICENSE file in the project root for more information.
using System;
-using System.Diagnostics.Contracts;
namespace System.Globalization
{
MIN_LUNISOLAR_YEAR,
MAX_LUNISOLAR_YEAR));
}
- Contract.EndContractBlock();
return s_yinfo[lunarYear - MIN_LUNISOLAR_YEAR, index];
}
using System;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
namespace System.Globalization
{
}
- [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));
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
- Contract.EndContractBlock();
return (helper.ToFourDigitYear(year, this.TwoDigitYearMax));
}
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Globalization
{
-120000,
120000));
}
- Contract.EndContractBlock();
// Get the date in UmAlQura calendar.
int y = GetDatePart(time, DatePartYear);
int m = GetDatePart(time, DatePartMonth);
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;
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
- Contract.EndContractBlock();
if (year < 100)
{
// 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;
// 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;
{
throw new ArgumentNullException(nameof(g));
}
- Contract.EndContractBlock();
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.All);
// 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);
}
}
using System.Runtime.InteropServices;
using System.Text;
using System.Globalization;
-using System.Diagnostics.Contracts;
namespace System.IO
{
/// <summary>
/// Provides centralized methods for creating exceptions for System.IO.FileSystem.
/// </summary>
- [Pure]
internal static class Error
{
internal static Exception GetStreamIsClosed()
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Text;
namespace System.IO
// 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)
// 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)
return path.Substring(offset, count);
}
- [Pure]
public static string GetFileNameWithoutExtension(string path)
{
if (path == null)
// 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)
{
if (path1 == null || path2 == null)
throw new ArgumentNullException((path1 == null) ? nameof(path1) : nameof(path2));
- Contract.EndContractBlock();
PathInternal.CheckInvalidPathChars(path1);
PathInternal.CheckInvalidPathChars(path2);
{
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);
{
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);
{
throw new ArgumentNullException(nameof(paths));
}
- Contract.EndContractBlock();
int finalSize = 0;
int firstComponent = 0;
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.IO
{
// 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;
{
throw new ArgumentOutOfRangeException(nameof(access));
}
- Contract.EndContractBlock();
if (_isOpen)
{
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);
/// </summary>
public override bool CanRead
{
- [Pure]
get { return _isOpen && (_access & FileAccess.Read) != 0; }
}
/// </summary>
public override bool CanSeek
{
- [Pure]
get { return _isOpen; }
}
/// </summary>
public override bool CanWrite
{
- [Pure]
get { return _isOpen && (_access & FileAccess.Write) != 0; }
}
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);
}
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<Int32>(cancellationToken);
{
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();
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);
using System;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
{
return (int)_unmanagedStream.Capacity;
}
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
set
{
throw new IOException(SR.IO_FixedCapacity);
{
if (stream == null)
throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream);
- Contract.EndContractBlock();
byte[] buffer = ToArray();
if (!destination.CanWrite)
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
- Contract.EndContractBlock();
return _unmanagedStream.CopyToAsync(destination, bufferSize, cancellationToken);
}
**
===========================================================*/
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public override String ToString()
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format)
{
- Contract.Ensures(Contract.Result<String>() != null);
return ToString(format, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return ToString(format, NumberFormatInfo.GetInstance(provider));
}
private String ToString(String format, NumberFormatInfo info)
{
- Contract.Ensures(Contract.Result<String>() != null);
-
if (m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x'))
{
uint temp = (uint)(m_value & 0x0000FFFF);
**
===========================================================*/
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
return m_value;
}
- [Pure]
public override String ToString()
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
- [Pure]
public String ToString(String format)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
- [Pure]
public String ToString(IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
- [Pure]
public String ToString(String format, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != 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);
// 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);
// 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);
// 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)
// 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);
// IConvertible implementation
//
- [Pure]
public TypeCode GetTypeCode()
{
return TypeCode.Int32;
**
===========================================================*/
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public override String ToString()
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, format, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, format, NumberFormatInfo.GetInstance(provider));
}
//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;
{
return max;
}
-
+
return value;
}
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode));
}
- Contract.EndContractBlock();
if (Abs(value) < doubleRoundLimit)
{
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));
}
//This class contains only static members and doesn't require serialization.
-using System.Diagnostics.Contracts;
using System.Runtime;
using System.Runtime.CompilerServices;
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidEnum, mode, nameof(MidpointRounding)), nameof(mode));
}
- Contract.EndContractBlock();
if (Abs(x) < singleRoundLimit)
{
using System.Reflection;
using System.Runtime.Versioning;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Resources
{
throw new ArgumentNullException(nameof(key));
if (Reader == null || _resCache == null)
throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet);
- Contract.EndContractBlock();
Object value = null;
ResourceLocator resLocation;
===========================================================*/
using System;
-using System.Diagnostics.Contracts;
namespace System.Runtime.Versioning
{
{
if (frameworkName == null)
throw new ArgumentNullException(nameof(frameworkName));
- Contract.EndContractBlock();
_frameworkName = frameworkName;
}
// 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;
// Provides a string representation of a byte.
public override String ToString()
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format)
{
- Contract.Ensures(Contract.Result<String>() != null);
return ToString(format, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return ToString(format, NumberFormatInfo.GetInstance(provider));
}
private String ToString(String format, NumberFormatInfo info)
{
- Contract.Ensures(Contract.Result<String>() != null);
-
if (m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x'))
{
uint temp = (uint)(m_value & 0x000000FF);
**
===========================================================*/
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
internal const float NegativeZero = (float)-0.0;
/// <summary>Determines whether the specified value is finite (zero, subnormal, or normal).</summary>
- [Pure]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsFinite(float f)
}
/// <summary>Determines whether the specified value is infinite.</summary>
- [Pure]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsInfinity(float f)
}
/// <summary>Determines whether the specified value is NaN.</summary>
- [Pure]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsNaN(float f)
}
/// <summary>Determines whether the specified value is negative.</summary>
- [Pure]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsNegative(float f)
}
/// <summary>Determines whether the specified value is negative infinity.</summary>
- [Pure]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsNegativeInfinity(float f)
}
/// <summary>Determines whether the specified value is normal.</summary>
- [Pure]
[NonVersionable]
// This is probably not worth inlining, it has branches and should be rarely called
public unsafe static bool IsNormal(float f)
}
/// <summary>Determines whether the specified value is positive infinity.</summary>
- [Pure]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsPositiveInfinity(float f)
}
/// <summary>Determines whether the specified value is subnormal.</summary>
- [Pure]
[NonVersionable]
// This is probably not worth inlining, it has branches and should be rarely called
public unsafe static bool IsSubnormal(float f)
public override String ToString()
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatSingle(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatSingle(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatSingle(m_value, format, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider));
}
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
-using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System
{
get
{
- Contract.Ensures(Contract.Result<StringComparer>() != null);
return s_invariantCulture;
}
}
{
get
{
- Contract.Ensures(Contract.Result<StringComparer>() != null);
return s_invariantCultureIgnoreCase;
}
}
{
get
{
- Contract.Ensures(Contract.Result<StringComparer>() != null);
return new CultureAwareComparer(CultureInfo.CurrentCulture, false);
}
}
{
get
{
- Contract.Ensures(Contract.Result<StringComparer>() != null);
return new CultureAwareComparer(CultureInfo.CurrentCulture, true);
}
}
{
get
{
- Contract.Ensures(Contract.Result<StringComparer>() != null);
return s_ordinal;
}
}
{
get
{
- Contract.Ensures(Contract.Result<StringComparer>() != null);
return s_ordinalIgnoreCase;
}
}
{
throw new ArgumentNullException(nameof(culture));
}
- Contract.Ensures(Contract.Result<StringComparer>() != null);
- Contract.EndContractBlock();
return new CultureAwareComparer(culture, ignoreCase);
}
{
throw new ArgumentNullException(nameof(obj));
}
- Contract.EndContractBlock();
string s = obj as string;
if (s != null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj);
}
- Contract.EndContractBlock();
if (_ignoreCase)
{
using System;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Text
{
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)
// Validate input
if (chars==null)
throw new ArgumentNullException("chars");
- Contract.EndContractBlock();
fixed (char* pChars = chars)
return GetByteCount(pChars, chars.Length, null);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
// Call it with empty encoder
return GetByteCount(chars, count, null);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index);
- Contract.EndContractBlock();
int byteCount = bytes.Length - byteIndex;
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)
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return GetBytes(chars, charCount, bytes, byteCount, null);
}
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)
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return GetCharCount(bytes, count, null);
}
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)
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return GetChars(bytes, byteCount, chars, charCount, null);
}
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;
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;
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;
using System.Text;
using System;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Text
{
{
if (value == null)
throw new ArgumentNullException(nameof(value));
- Contract.EndContractBlock();
// Can't change fallback if buffer is wrong
if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0)
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
byte[] arrbyte = new byte[count];
int index;
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];
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars),
SR.ArgumentOutOfRange_IndexCountBuffer);
- Contract.EndContractBlock();
bytesUsed = 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;
using System.Runtime.Serialization;
using System.Text;
using System;
-using System.Diagnostics.Contracts;
namespace System.Text
{
throw new ArgumentOutOfRangeException(nameof(bytes),
SR.ArgumentOutOfRange_IndexCountBuffer);
- Contract.EndContractBlock();
// Avoid null fixed problem
if (bytes.Length == 0)
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
// Remember the flush
_mustFlush = flush;
throw new ArgumentOutOfRangeException(nameof(charIndex),
SR.ArgumentOutOfRange_Index);
- Contract.EndContractBlock();
// Avoid empty input fixed problem
if (bytes.Length == 0)
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
// Remember our flush
_mustFlush = flush;
throw new ArgumentOutOfRangeException(nameof(chars),
SR.ArgumentOutOfRange_IndexCountBuffer);
- Contract.EndContractBlock();
// Avoid empty input problem
if (bytes.Length == 0)
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;
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Text
{
{
if (replacement == null)
throw new ArgumentNullException(nameof(replacement));
- Contract.EndContractBlock();
// Make sure it doesn't have bad surrogate pairs
bool bFoundHigh = false;
using System.Text;
using System;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Text
{
{
if (value == null)
throw new ArgumentNullException(nameof(value));
- Contract.EndContractBlock();
// Can't change fallback if buffer is wrong
if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0)
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
char[] arrChar = new char[count];
int index;
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];
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes),
SR.ArgumentOutOfRange_IndexCountBuffer);
- Contract.EndContractBlock();
charsUsed = 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;
//
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Threading;
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
using System;
using System.Runtime.Serialization;
-using System.Diagnostics.Contracts;
namespace System.Text
{
throw new ArgumentOutOfRangeException(nameof(charUnknownLow),
SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF));
}
- Contract.EndContractBlock();
int iTemp = Char.ConvertToUtf32(charUnknownHigh, charUnknownLow);
throw new ArgumentOutOfRangeException(nameof(CharUnknownLow),
SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF));
}
- Contract.EndContractBlock();
_charUnknownHigh = charUnknownHigh;
_charUnknownLow = charUnknownLow;
using System.Text;
using System;
-using System.Diagnostics.Contracts;
namespace System.Text
{
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(chars),
SR.ArgumentOutOfRange_IndexCountBuffer);
- Contract.EndContractBlock();
// Avoid empty input problem
if (chars.Length == 0)
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
_mustFlush = flush;
_throwOnOverflow = true;
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException(nameof(byteIndex),
SR.ArgumentOutOfRange_Index);
- Contract.EndContractBlock();
if (chars.Length == 0)
chars = new char[1];
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
_mustFlush = flush;
_throwOnOverflow = true;
throw new ArgumentOutOfRangeException(nameof(bytes),
SR.ArgumentOutOfRange_IndexCountBuffer);
- Contract.EndContractBlock();
// Avoid empty input problem
if (chars.Length == 0)
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;
using System;
using System.Runtime;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Text
{
// 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;
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.
using System.Diagnostics;
using System.Globalization;
-using System.Diagnostics.Contracts;
using System.Threading;
using System.Runtime.Serialization;
using System.Diagnostics.CodeAnalysis;
{
throw new ArgumentOutOfRangeException(nameof(codePage));
}
- Contract.EndContractBlock();
// Remember code page
_codePage = codePage;
{
throw new ArgumentOutOfRangeException(nameof(codePage));
}
- Contract.EndContractBlock();
// Remember code page
_codePage = codePage;
// 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<byte[]>() != null);
return Convert(srcEncoding, dstEncoding, bytes, 0, bytes.Length);
}
// 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)
{
throw new ArgumentNullException(nameof(bytes),
SR.ArgumentNull_Array);
}
- Contract.Ensures(Contract.Result<byte[]>() != null);
return dstEncoding.GetBytes(srcEncoding.GetChars(bytes, index, count));
}
EncodingProvider.AddProvider(provider);
}
- [Pure]
public static Encoding GetEncoding(int codepage)
{
Encoding result = EncodingProvider.GetEncodingFromProvider(codepage);
nameof(codepage), SR.Format(SR.ArgumentOutOfRange_Range, 0, 65535));
}
- Contract.EndContractBlock();
switch (codepage)
{
return UTF8;
}
- [Pure]
public static Encoding GetEncoding(int codepage,
EncoderFallback encoderFallback, DecoderFallback decoderFallback)
{
// 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);
// 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)
{
}
// 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<byte>();
if (value == null)
throw new ArgumentNullException(nameof(value));
- Contract.EndContractBlock();
encoderFallback = value;
}
if (value == null)
throw new ArgumentNullException(nameof(value));
- Contract.EndContractBlock();
decoderFallback = value;
}
// Returns the number of bytes required to encode the given character
// array.
//
- [Pure]
public virtual int GetByteCount(char[] chars)
{
if (chars == null)
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);
// 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)
if (index > s.Length - count)
throw new ArgumentOutOfRangeException(nameof(index),
SR.ArgumentOutOfRange_IndexCount);
- Contract.EndContractBlock();
unsafe
{
// 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)
{
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
char[] arrChar = new char[count];
int index;
// Returns a byte array containing the encoded representation of the given
// character array.
//
- [Pure]
public virtual byte[] GetBytes(char[] chars)
{
if (chars == null)
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)];
// 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];
// 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)
if (index > s.Length - count)
throw new ArgumentOutOfRangeException(nameof(index),
SR.ArgumentOutOfRange_IndexCount);
- Contract.EndContractBlock();
unsafe
{
{
if (s == null)
throw new ArgumentNullException(nameof(s));
- Contract.EndContractBlock();
return GetBytes(s.ToCharArray(), charIndex, charCount, bytes, byteIndex);
}
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];
// Returns the number of characters produced by decoding the given byte
// array.
//
- [Pure]
public virtual int GetCharCount(byte[] bytes)
{
if (bytes == null)
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)
{
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
byte[] arrbyte = new byte[count];
int index;
// Returns a character array containing the decoded representation of a
// given byte array.
//
- [Pure]
public virtual char[] GetChars(byte[] bytes)
{
if (bytes == null)
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)];
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];
if (byteCount < 0)
throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return String.CreateStringFromEncoding(bytes, byteCount, this);
}
// 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
// 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
// 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);
}
//
// Internally we override this for performance
//
- [Pure]
public virtual String GetString(byte[] bytes, int index, int count)
{
return new String(GetChars(bytes, index, count));
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);
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)
{
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
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)
{
// 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;
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)
// Validate input
if (s==null)
throw new ArgumentNullException("s");
- Contract.EndContractBlock();
fixed (char* pChars = s)
return GetByteCount(pChars, s.Length, null);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
// Call it with empty encoder
return GetByteCount(chars, count, null);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index);
- Contract.EndContractBlock();
int byteCount = bytes.Length - byteIndex;
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)
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return GetBytes(chars, charCount, bytes, byteCount, null);
}
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)
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return GetCharCount(bytes, count, null);
}
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)
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return GetChars(bytes, byteCount, chars, charCount, null);
}
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;
using System;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Text
{
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;
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;
using System.Threading;
using System.Globalization;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Collections.Generic;
namespace System.Text
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
}
- Contract.EndContractBlock();
if (value == null)
{
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.Format(SR.ArgumentOutOfRange_MustBePositive, nameof(capacity)));
}
- Contract.EndContractBlock();
if (capacity == 0)
{
{
throw new ArgumentNullException(nameof(info));
}
- Contract.EndContractBlock();
int persistedCapacity = 0;
string persistedString = null;
{
throw new ArgumentNullException(nameof(info));
}
- Contract.EndContractBlock();
AssertInvariants();
info.AddValue(MaxCapacityField, m_MaxCapacity);
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
}
- Contract.EndContractBlock();
if (Capacity != value)
{
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity);
}
- Contract.EndContractBlock();
if (Capacity < capacity)
Capacity = capacity;
/// <param name="length">The number of characters to read in this builder.</param>
public string ToString(int startIndex, int length)
{
- Contract.Ensures(Contract.Result<String>() != null);
-
int currentLength = this.Length;
if (startIndex < 0)
{
{
get
{
- Contract.Ensures(Contract.Result<int>() >= 0);
return m_ChunkOffset + m_ChunkLength;
}
set
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
}
- Contract.EndContractBlock();
int originalCapacity = Capacity;
{
throw new ArgumentOutOfRangeException(nameof(repeatCount), SR.ArgumentOutOfRange_NegativeCount);
}
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- Contract.EndContractBlock();
if (repeatCount == 0)
{
{
throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GenericPositive);
}
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- Contract.EndContractBlock();
if (value == null)
{
/// <param name="value">The string to append.</param>
public StringBuilder Append(String value)
{
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
-
if (value != null)
{
// We could have just called AppendHelper here; this is a hand-specialization of that code.
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GenericPositive);
}
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
if (value == null)
{
{
throw new ArgumentException(SR.ArgumentOutOfRange_OffsetOut);
}
- Contract.EndContractBlock();
CopyTo(sourceIndex, new Span<char>(destination).Slice(destinationIndex), count);
}
{
throw new ArgumentException(SR.Arg_LongerThanSrcString);
}
- Contract.EndContractBlock();
AssertInvariants();
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- Contract.EndContractBlock();
int currentLength = Length;
if ((uint)index > (uint)currentLength)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index);
}
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- Contract.EndContractBlock();
if (Length == length && startIndex == 0)
{
public StringBuilder Append(char value)
{
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
-
if (m_ChunkLength < m_ChunkChars.Length)
{
m_ChunkChars[m_ChunkLength++] = value;
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
}
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- Contract.EndContractBlock();
if (value != null)
{
public StringBuilder Insert(int index, char value)
{
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
-
unsafe
{
Insert(index, &value, 1);
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
}
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- Contract.EndContractBlock();
if (value != null)
Insert(index, value, 0, value.Length);
public StringBuilder Insert(int index, char[] value, int startIndex, int charCount)
{
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
-
int currentLength = Length;
if ((uint)index > (uint)currentLength)
{
public StringBuilder Insert(int index, ReadOnlySpan<char> value)
{
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- Contract.EndContractBlock();
-
if ((uint)index > (uint)Length)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
string paramName = (format == null) ? nameof(format) : nameof(args);
throw new ArgumentNullException(paramName);
}
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
return AppendFormatHelper(null, format, new ParamsArray(args));
}
string paramName = (format == null) ? nameof(format) : nameof(args);
throw new ArgumentNullException(paramName);
}
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
return AppendFormatHelper(provider, format, new ParamsArray(args));
}
{
throw new ArgumentNullException(nameof(format));
}
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- Contract.EndContractBlock();
int pos = 0;
int len = format.Length;
/// </remarks>
public StringBuilder Replace(String oldValue, String newValue, int startIndex, int count)
{
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
-
int currentLength = Length;
if ((uint)startIndex > (uint)currentLength)
{
/// <param name="count">The number of characters to read in this builder.</param>
public StringBuilder Replace(char oldChar, char newChar, int startIndex, int count)
{
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
-
int currentLength = Length;
if ((uint)startIndex > (uint)currentLength)
{
/// </remarks>
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();
using System;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Globalization;
namespace System.Text
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)
// Validate input
if (s==null)
throw new ArgumentNullException("s");
- Contract.EndContractBlock();
fixed (char* pChars = s)
return GetByteCount(pChars, s.Length, null);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
// Call it with empty encoder
return GetByteCount(chars, count, null);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index);
- Contract.EndContractBlock();
int byteCount = bytes.Length - byteIndex;
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)
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return GetBytes(chars, charCount, bytes, byteCount, null);
}
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)
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return GetCharCount(bytes, count, null);
}
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)
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return GetChars(bytes, byteCount, chars, charCount, null);
}
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;
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
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;
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.
using System;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Text
{
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)
// Validate input
if (s==null)
throw new ArgumentNullException("s");
- Contract.EndContractBlock();
fixed (char* pChars = s)
return GetByteCount(pChars, s.Length, null);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
// Call it with empty encoder
return GetByteCount(chars, count, null);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index);
- Contract.EndContractBlock();
int byteCount = bytes.Length - byteIndex;
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)
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return GetBytes(chars, charCount, bytes, byteCount, null);
}
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)
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return GetCharCount(bytes, count, null);
}
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)
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return GetChars(bytes, byteCount, chars, charCount, null);
}
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;
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
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.
using System;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Globalization;
namespace System.Text
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)
// Validate input
if (chars==null)
throw new ArgumentNullException("s");
- Contract.EndContractBlock();
fixed (char* pChars = chars)
return GetByteCount(pChars, chars.Length, null);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
// Call it with empty encoder
return GetByteCount(chars, count, null);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index);
- Contract.EndContractBlock();
int byteCount = bytes.Length - byteIndex;
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)
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return GetBytes(chars, charCount, bytes, byteCount, null);
}
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)
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return GetCharCount(bytes, count, null);
}
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)
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return GetChars(bytes, byteCount, chars, charCount, null);
}
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;
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;
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);
using System;
using System.Globalization;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Text
{
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)
// Validate input
if (s==null)
throw new ArgumentNullException("s");
- Contract.EndContractBlock();
fixed (char* pChars = s)
return GetByteCount(pChars, s.Length, null);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
// Call it with empty encoder
return GetByteCount(chars, count, null);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index);
- Contract.EndContractBlock();
int byteCount = bytes.Length - byteIndex;
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)
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return GetBytes(chars, charCount, bytes, byteCount, null);
}
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)
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return GetCharCount(bytes, count, null);
}
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)
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
return GetChars(bytes, byteCount, chars, charCount, null);
}
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;
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;
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.
===========================================================*/
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.ExceptionServices;
using System.Runtime.Serialization;
{
throw new InvalidOperationException(SR.InvalidOperation_CannotSupressFlowMultipleTimes);
}
- Contract.EndContractBlock();
executionContext = executionContext.ShallowClone(isFlowSuppressed: true);
var asyncFlowControl = new AsyncFlowControl();
{
throw new InvalidOperationException(SR.InvalidOperation_CannotRestoreUnsupressedFlow);
}
- Contract.EndContractBlock();
currentThread.ExecutionContext = executionContext.ShallowClone(isFlowSuppressed: false);
}
{
throw new InvalidOperationException(SR.InvalidOperation_AsyncFlowCtrlCtxMismatch);
}
- Contract.EndContractBlock();
_thread = null;
ExecutionContext.RestoreFlow();
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
-using System.Diagnostics.Contracts;
using System.Globalization;
namespace System
{
if (Ticks == TimeSpan.MinValue.Ticks)
throw new OverflowException(SR.Overflow_Duration);
- Contract.EndContractBlock();
return new TimeSpan(_ticks >= 0 ? _ticks : -_ticks);
}
{
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))
{
if (Ticks == TimeSpan.MinValue.Ticks)
throw new OverflowException(SR.Overflow_NegateTwosCompNum);
- Contract.EndContractBlock();
return new TimeSpan(-_ticks);
}
**
===========================================================*/
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Converts the current value to a String in base-10 with no extra padding.
public override String ToString()
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
}
**
===========================================================*/
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// The base 10 representation of the number with no extra padding.
public override String ToString()
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
}
**
===========================================================*/
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public override String ToString()
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt64(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt64(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt64(m_value, format, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt64(m_value, format, NumberFormatInfo.GetInstance(provider));
}
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;
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;
}
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;
}
using System.Globalization;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Text;
namespace System
if (revision < 0)
throw new ArgumentOutOfRangeException(nameof(revision), SR.ArgumentOutOfRange_Version);
- Contract.EndContractBlock();
_Major = major;
_Minor = minor;
if (build < 0)
throw new ArgumentOutOfRangeException(nameof(build), SR.ArgumentOutOfRange_Version);
- Contract.EndContractBlock();
_Major = major;
_Minor = minor;
if (minor < 0)
throw new ArgumentOutOfRangeException(nameof(minor), SR.ArgumentOutOfRange_Version);
- Contract.EndContractBlock();
_Major = major;
_Minor = minor;
{
if ((Object)v1 == null)
throw new ArgumentNullException(nameof(v1));
- Contract.EndContractBlock();
return (v1.CompareTo(v2) < 0);
}
{
if ((Object)v1 == null)
throw new ArgumentNullException(nameof(v1));
- Contract.EndContractBlock();
return (v1.CompareTo(v2) <= 0);
}
namespace Internal
{
-
/// <summary>A class for common padding constants and eventually routines.</summary>
internal static class PaddingHelpers
{
using System;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
namespace Microsoft.Win32
{
using System;
- using System.Diagnostics.Contracts;
+ using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
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
using System;
using System.Buffers;
using System.Collections.Generic;
-using System.Diagnostics.Contracts;
+using System.Diagnostics;
using System.IO;
using System.Text;
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;
static private void ValidateKeyName(string name)
{
- Contract.Ensures(name != null);
if (name == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.name);
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
{
if ((object)type == null)
throw new ArgumentNullException(nameof(type));
- Contract.EndContractBlock();
if (type is System.Reflection.Emit.TypeBuilder)
throw new NotSupportedException(SR.NotSupported_CreateInstanceWithTypeBuilder);
{
if ((object)type == null)
throw new ArgumentNullException(nameof(type));
- Contract.EndContractBlock();
RuntimeType rt = type.UnderlyingSystemType as RuntimeType;
{
get
{
- Contract.Ensures(Contract.Result<AppDomain>() != null);
return Thread.GetDomain();
}
}
{
if (name == null)
throw new ArgumentNullException(nameof(name));
- Contract.EndContractBlock();
lock (((ICollection)LocalStore).SyncRoot)
{
{
if (name == null)
throw new ArgumentNullException(nameof(name));
- Contract.EndContractBlock();
object data;
lock (((ICollection)LocalStore).SyncRoot)
private void SetupFusionStore(AppDomainSetup info, AppDomainSetup oldInfo)
{
- Contract.Requires(info != null);
+ Debug.Assert(info != null);
if (info.ApplicationBase == null)
{
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];
using System.Security;
using Path = System.IO.Path;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
using System.Collections.Generic;
internal sealed class AppDomainSetup
public String ApplicationBase
{
- [Pure]
get
{
return Value[(int)LoaderInformation.ApplicationBaseValue];
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.
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
{
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- Contract.Ensures(Contract.Result<ReadOnlyCollection<T>>() != null);
// T[] implements IList<T>.
return new ReadOnlyCollection<T>(array);
{
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)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType);
if (length < 0)
ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
- Contract.Ensures(Contract.Result<Array>() != null);
- Contract.Ensures(Contract.Result<Array>().Length == length);
- Contract.Ensures(Contract.Result<Array>().Rank == 1);
- Contract.EndContractBlock();
RuntimeType t = elementType.UnderlyingSystemType as RuntimeType;
if (t == null)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length1, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
if (length2 < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length2, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
- Contract.Ensures(Contract.Result<Array>() != null);
- Contract.Ensures(Contract.Result<Array>().Rank == 2);
- Contract.Ensures(Contract.Result<Array>().GetLength(0) == length1);
- Contract.Ensures(Contract.Result<Array>().GetLength(1) == length2);
RuntimeType t = elementType.UnderlyingSystemType as RuntimeType;
if (t == null)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length2, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
if (length3 < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length3, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
- Contract.Ensures(Contract.Result<Array>() != null);
- Contract.Ensures(Contract.Result<Array>().Rank == 3);
- Contract.Ensures(Contract.Result<Array>().GetLength(0) == length1);
- Contract.Ensures(Contract.Result<Array>().GetLength(1) == length2);
- Contract.Ensures(Contract.Result<Array>().GetLength(2) == length3);
RuntimeType t = elementType.UnderlyingSystemType as RuntimeType;
if (t == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths);
if (lengths.Length == 0)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank);
- Contract.Ensures(Contract.Result<Array>() != null);
- Contract.Ensures(Contract.Result<Array>().Rank == lengths.Length);
- Contract.EndContractBlock();
RuntimeType t = elementType.UnderlyingSystemType as RuntimeType;
if (t == null)
}
if (lengths.Length == 0)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank);
- Contract.Ensures(Contract.Result<Array>() != null);
- Contract.Ensures(Contract.Result<Array>().Rank == lengths.Length);
- Contract.EndContractBlock();
int[] intLengths = new int[lengths.Length];
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RanksAndBounds);
if (lengths.Length == 0)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank);
- Contract.Ensures(Contract.Result<Array>() != null);
- Contract.Ensures(Contract.Result<Array>().Rank == lengths.Length);
- Contract.EndContractBlock();
RuntimeType t = elementType.UnderlyingSystemType as RuntimeType;
if (t == null)
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);
}
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices);
if (Rank != indices.Length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices);
- Contract.EndContractBlock();
TypedReference elemref = new TypedReference();
fixed (int* pIndices = &indices[0])
{
if (Rank != 1)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need1DArray);
- Contract.EndContractBlock();
TypedReference elemref = new TypedReference();
InternalGetReference(&elemref, 1, &index);
{
if (Rank != 2)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need2DArray);
- Contract.EndContractBlock();
int* pIndices = stackalloc int[2];
pIndices[0] = index1;
{
if (Rank != 3)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need3DArray);
- Contract.EndContractBlock();
int* pIndices = stackalloc int[3];
pIndices[0] = index1;
{
if (index > Int32.MaxValue || index < Int32.MinValue)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
- Contract.EndContractBlock();
return this.GetValue((int)index);
}
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);
}
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);
}
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices);
if (Rank != indices.Length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices);
- Contract.EndContractBlock();
int[] intIndices = new int[indices.Length];
{
if (Rank != 1)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need1DArray);
- Contract.EndContractBlock();
TypedReference elemref = new TypedReference();
InternalGetReference(&elemref, 1, &index);
{
if (Rank != 2)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need2DArray);
- Contract.EndContractBlock();
int* pIndices = stackalloc int[2];
pIndices[0] = index1;
{
if (Rank != 3)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need3DArray);
- Contract.EndContractBlock();
int* pIndices = stackalloc int[3];
pIndices[0] = index1;
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices);
if (Rank != indices.Length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices);
- Contract.EndContractBlock();
TypedReference elemref = new TypedReference();
fixed (int* pIndices = &indices[0])
{
if (index > Int32.MaxValue || index < Int32.MinValue)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
- Contract.EndContractBlock();
this.SetValue(value, (int)index);
}
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);
}
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);
}
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices);
if (Rank != indices.Length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices);
- Contract.EndContractBlock();
int[] intIndices = new int[indices.Length];
public extern int Length
{
- [Pure]
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
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);
}
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
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);
{
if (comparer == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparer);
- Contract.EndContractBlock();
int ret = 0;
// 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<int>() >= array.GetLowerBound(0) && Contract.Result<int>() <= array.GetUpperBound(0)) || (Contract.Result<int>() < array.GetLowerBound(0) && ~Contract.Result<int>() <= array.GetUpperBound(0) + 1));
- Contract.EndContractBlock();
int lb = array.GetLowerBound(0);
return BinarySearch(array, lb, array.Length, value, null);
}
// 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);
// 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);
}
// 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();
[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>(T[] array, T value)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
- Contract.EndContractBlock();
return BinarySearch<T>(array, 0, array.Length, value, null);
}
- [Pure]
public static int BinarySearch<T>(T[] array, T value, System.Collections.Generic.IComparer<T> comparer)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
- Contract.EndContractBlock();
return BinarySearch<T>(array, 0, array.Length, value, comparer);
}
- [Pure]
public static int BinarySearch<T>(T[] array, int index, int length, T value)
{
return BinarySearch<T>(array, index, length, value, null);
}
- [Pure]
public static int BinarySearch<T>(T[] array, int index, int length, T value, System.Collections.Generic.IComparer<T> comparer)
{
if (array == null)
if (array.Length - index < length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
- Contract.EndContractBlock();
return ArraySortHelper<T>.Default.BinarySearch(array, index, length, value, comparer);
}
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter);
}
- Contract.Ensures(Contract.Result<TOutput[]>() != null);
- Contract.Ensures(Contract.Result<TOutput[]>().Length == array.Length);
- Contract.EndContractBlock();
TOutput[] newArray = new TOutput[array.Length];
for (int i = 0; i < array.Length; i++)
// Array.Copy internally. If you aren't using ICollection explicitly,
// call Array.Copy to avoid an extra indirection.
//
- [Pure]
public void CopyTo(Array array, int index)
{
if (array != null && array.Rank != 1)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
- Contract.EndContractBlock();
// Note: Array.Copy throws a RankException and we want a consistent ArgumentException for all the IList CopyTo methods.
Array.Copy(this, GetLowerBound(0), array, index, Length);
}
- [Pure]
public void CopyTo(Array array, long index)
{
if (index > Int32.MaxValue || index < Int32.MinValue)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
- Contract.EndContractBlock();
this.CopyTo(array, (int)index);
}
internal static readonly T[] Value = new T[0];
}
- [Pure]
public static T[] Empty<T>()
{
- Contract.Ensures(Contract.Result<T[]>() != null);
- Contract.Ensures(Contract.Result<T[]>().Length == 0);
- Contract.EndContractBlock();
-
return EmptyArray<T>.Value;
}
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
- Contract.EndContractBlock();
for (int i = 0; i < array.Length; i++)
{
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
- Contract.EndContractBlock();
List<T> list = new List<T>();
for (int i = 0; i < array.Length; i++)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- Contract.Ensures(Contract.Result<int>() < array.Length);
- Contract.EndContractBlock();
return FindIndex(array, 0, array.Length, match);
}
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- Contract.Ensures(Contract.Result<int>() < array.Length);
- Contract.EndContractBlock();
return FindIndex(array, startIndex, array.Length - startIndex, match);
}
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
- Contract.Ensures(Contract.Result<int>() < array.Length);
- Contract.EndContractBlock();
int endIndex = startIndex + count;
for (int i = startIndex; i < endIndex; i++)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
- Contract.EndContractBlock();
for (int i = array.Length - 1; i >= 0; i--)
{
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- Contract.EndContractBlock();
return FindLastIndex(array, array.Length - 1, array.Length, match);
}
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- Contract.EndContractBlock();
return FindLastIndex(array, startIndex, startIndex + 1, match);
}
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
- Contract.EndContractBlock();
if (array.Length == 0)
{
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action);
}
- Contract.EndContractBlock();
for (int i = 0; i < array.Length; i++)
{
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
- Contract.Ensures(Contract.Result<int>() < array.GetLowerBound(0) + array.Length);
- Contract.EndContractBlock();
int lb = array.GetLowerBound(0);
return IndexOf(array, value, lb, array.Length);
}
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
- Contract.Ensures(Contract.Result<int>() < array.GetLowerBound(0) + array.Length);
- Contract.EndContractBlock();
int lb = array.GetLowerBound(0);
return IndexOf(array, value, startIndex, array.Length - startIndex + lb);
}
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (array.Rank != 1)
ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported);
- Contract.Ensures(Contract.Result<int>() < array.GetLowerBound(0) + array.Length);
- Contract.EndContractBlock();
int lb = array.GetLowerBound(0);
if (startIndex < lb || startIndex > array.Length + lb)
return lb - 1;
}
- [Pure]
public static int IndexOf<T>(T[] array, T value)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- Contract.Ensures((Contract.Result<int>() < 0) ||
- (Contract.Result<int>() >= 0 && Contract.Result<int>() < array.Length && EqualityComparer<T>.Default.Equals(value, array[Contract.Result<int>()])));
- Contract.EndContractBlock();
return IndexOf(array, value, 0, array.Length);
}
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- Contract.Ensures(Contract.Result<int>() < array.Length);
- Contract.EndContractBlock();
return IndexOf(array, value, startIndex, array.Length - startIndex);
}
{
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
- Contract.Ensures(Contract.Result<int>() < array.Length);
- Contract.EndContractBlock();
return EqualityComparer<T>.Default.IndexOf(array, value, startIndex, count);
}
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
- Contract.Ensures(Contract.Result<int>() < array.GetLowerBound(0) + array.Length);
- Contract.EndContractBlock();
int lb = array.GetLowerBound(0);
return LastIndexOf(array, value, array.Length - 1 + lb, array.Length);
}
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
- Contract.Ensures(Contract.Result<int>() < array.GetLowerBound(0) + array.Length);
- Contract.EndContractBlock();
int lb = array.GetLowerBound(0);
return LastIndexOf(array, value, startIndex, startIndex + 1 - lb);
}
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
- Contract.Ensures(Contract.Result<int>() < array.GetLowerBound(0) + array.Length);
- Contract.EndContractBlock();
int lb = array.GetLowerBound(0);
if (array.Length == 0)
{
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- Contract.Ensures(Contract.Result<int>() < array.Length);
- Contract.EndContractBlock();
return LastIndexOf(array, value, array.Length - 1, array.Length);
}
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- Contract.Ensures(Contract.Result<int>() < 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));
}
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- Contract.Ensures(Contract.Result<int>() < array.Length);
- Contract.EndContractBlock();
if (array.Length == 0)
{
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
- Contract.EndContractBlock();
Reverse(array, array.GetLowerBound(0), array.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)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
- Contract.EndContractBlock();
Reverse(array, 0, array.Length);
}
ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
if (array.Length - index < length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
- Contract.EndContractBlock();
ref T p = ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData());
int i = index;
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
- Contract.EndContractBlock();
Sort(array, null, array.GetLowerBound(0), array.Length, null);
}
{
if (keys == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
- Contract.EndContractBlock();
Sort(keys, items, keys.GetLowerBound(0), keys.Length, null);
}
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
- Contract.EndContractBlock();
Sort(array, null, array.GetLowerBound(0), array.Length, comparer);
}
{
if (keys == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
- Contract.EndContractBlock();
Sort(keys, items, keys.GetLowerBound(0), keys.Length, comparer);
}
if (keys.Length - (index - keysLowerBound) < length || (items != null && (index - keysLowerBound) > items.Length - length))
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
- Contract.EndContractBlock();
if (length > 1)
{
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
- Contract.EndContractBlock();
Sort<T>(array, 0, array.Length, null);
}
{
if (keys == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
- Contract.EndContractBlock();
Sort<TKey, TValue>(keys, items, 0, keys.Length, null);
}
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
- Contract.EndContractBlock();
Sort<T>(array, 0, array.Length, comparer);
}
{
if (keys == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
- Contract.EndContractBlock();
Sort<TKey, TValue>(keys, items, 0, keys.Length, comparer);
}
ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
if (array.Length - index < length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
- Contract.EndContractBlock();
if (length > 1)
{
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)
{
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison);
}
- Contract.EndContractBlock();
ArraySortHelper<T>.Sort(array, 0, array.Length, comparison);
}
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
- Contract.EndContractBlock();
for (int i = 0; i < array.Length; i++)
{
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System
{
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
- Contract.EndContractBlock();
_array = array;
_offset = 0;
// 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;
ThrowInvalidOperationIfDefault();
if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
- Contract.EndContractBlock();
return _array[_offset + index];
}
ThrowInvalidOperationIfDefault();
if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
- Contract.EndContractBlock();
_array[_offset + index] = value;
}
ThrowInvalidOperationIfDefault();
if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
- Contract.EndContractBlock();
return _array[_offset + index];
}
internal Enumerator(ArraySegment<T> 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;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Security;
namespace System
#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);
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
#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);
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);
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))
#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;
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
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
if (!type.IsSubclassOf(typeof(Attribute)) && type != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
- Contract.EndContractBlock();
switch (element.MemberType)
{
{
if (element == null)
throw new ArgumentNullException(nameof(element));
- Contract.EndContractBlock();
switch (element.MemberType)
{
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
- Contract.EndContractBlock();
switch (element.MemberType)
{
if (element.Member == null)
throw new ArgumentException(SR.Argument_InvalidParameterInfo, nameof(element));
- Contract.EndContractBlock();
MemberInfo member = element.Member;
if (member.MemberType == MemberTypes.Method && inherit)
if (element.Member == null)
throw new ArgumentException(SR.Argument_InvalidParameterInfo, nameof(element));
- Contract.EndContractBlock();
MemberInfo member = element.Member;
if (member.MemberType == MemberTypes.Method && inherit)
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
- Contract.EndContractBlock();
MemberInfo member = element.Member;
{
if (element == null)
throw new ArgumentNullException(nameof(element));
- Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
}
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
- Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
}
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
- Contract.EndContractBlock();
return element.IsDefined(attributeType, false);
}
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
- Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
}
{
if (element == null)
throw new ArgumentNullException(nameof(element));
- Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
}
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
- Contract.EndContractBlock();
return element.IsDefined(attributeType, false);
}
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
- using System.Diagnostics.Contracts;
internal enum LogLevel
{
#endif
}
- [Pure]
[Conditional("_LOGGING")]
static public void Log(String message)
{
System.Diagnostics.Log.Trace(Environment.NewLine);
}
- [Pure]
[Conditional("_LOGGING")]
static public void Log(String switchName, String message)
{
return ((int)logSwitch.MinimumLevel <= (int)level);
}
- [Pure]
[Conditional("_LOGGING")]
public static void Log(String switchName, LogLevel level, params Object[] messages)
{
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)
{
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
using System.Security;
using System.Runtime;
===========================================================*/
using System.Globalization;
-using System.Diagnostics.Contracts;
namespace System.Collections
{
{
throw new ArgumentNullException(nameof(culture));
}
- Contract.EndContractBlock();
m_compareInfo = culture.CompareInfo;
}
//
-using System.Diagnostics.Contracts;
namespace System.Collections
{
{
throw new ArgumentNullException(nameof(obj));
}
- Contract.EndContractBlock();
if (_hcp != null)
return _hcp.GetHashCode(obj);
**
===========================================================*/
-using System.Diagnostics.Contracts;
namespace System.Collections
{
if (array.Length - index < this.Count)
throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index));
- Contract.EndContractBlock();
// the actual copy is a NOP
}
{
throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
- Contract.EndContractBlock();
return null;
}
set
if ((value != null) && (!value.GetType().IsSerializable))
throw new ArgumentException(SR.Argument_NotSerializable, nameof(value));
- Contract.EndContractBlock();
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
if ((value != null) && (!value.GetType().IsSerializable))
throw new ArgumentException(SR.Argument_NotSerializable, nameof(value));
- Contract.EndContractBlock();
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.Versioning;
namespace System.Collections.Generic
internal static int InternalBinarySearch(T[] array, int index, int length, T value, IComparer<T> 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;
internal static void IntrospectiveSort(T[] keys, int left, int length, Comparison<T> 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;
private static void IntroSort(T[] keys, int lo, int hi, int depthLimit, Comparison<T> 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)
{
private static int PickPivotAndPartition(T[] keys, int lo, int hi, Comparison<T> 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<int>() >= lo && Contract.Result<int>() <= 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);
private static void Heapsort(T[] keys, int lo, int hi, Comparison<T> 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)
private static void DownHeap(T[] keys, int i, int n, int lo, Comparison<T> 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;
private static void InsertionSort(T[] keys, int lo, int hi, Comparison<T> 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;
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)
{
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;
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)
{
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<int>() >= lo && Contract.Result<int>() <= 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);
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)
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;
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;
private static void SwapIfGreaterWithItems(TKey[] keys, TValue[] values, IComparer<TKey> 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)
{
internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, int length, IComparer<TKey> 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;
private static void IntroSort(TKey[] keys, TValue[] values, int lo, int hi, int depthLimit, IComparer<TKey> 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)
{
private static int PickPivotAndPartition(TKey[] keys, TValue[] values, int lo, int hi, IComparer<TKey> 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<int>() >= lo && Contract.Result<int>() <= 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);
private static void Heapsort(TKey[] keys, TValue[] values, int lo, int hi, IComparer<TKey> 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)
private static void DownHeap(TKey[] keys, TValue[] values, int i, int n, int lo, IComparer<TKey> 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);
private static void InsertionSort(TKey[] keys, TValue[] values, int lo, int hi, IComparer<TKey> 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;
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;
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)
{
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<int>() >= lo && Contract.Result<int>() <= 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);
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)
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);
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;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
//using System.Globalization;
using System.Runtime.CompilerServices;
using System.Security;
public static Comparer<T> Create(Comparison<T> comparison)
{
- Contract.Ensures(Contract.Result<Comparer<T>>() != null);
-
if (comparison == null)
throw new ArgumentNullException(nameof(comparison));
using System;
using System.Collections;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
{
get
{
- Contract.Ensures(Contract.Result<KeyCollection>() != null);
if (keys == null) keys = new KeyCollection(this);
return keys;
}
{
get
{
- Contract.Ensures(Contract.Result<ValueCollection>() != null);
if (values == null) values = new ValueCollection(this);
return values;
}
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
-using System.Diagnostics.Contracts;
namespace System.Collections.Generic
{
// as possible and define most of the creation logic in a non-generic class.
public static EqualityComparer<T> Default { get; } = (EqualityComparer<T>)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)
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal class GenericEqualityComparer<T> : EqualityComparer<T> where T : IEquatable<T>
{
- [Pure]
public override bool Equals(T x, T y)
{
if (x != null)
return true;
}
- [Pure]
public override int GetHashCode(T obj) => obj?.GetHashCode() ?? 0;
internal override int IndexOf(T[] array, T value, int startIndex, int count)
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal sealed class NullableEqualityComparer<T> : EqualityComparer<T?> where T : struct, IEquatable<T>
{
- [Pure]
public override bool Equals(T? x, T? y)
{
if (x.HasValue)
return true;
}
- [Pure]
public override int GetHashCode(T? obj) => obj.GetHashCode();
internal override int IndexOf(T?[] array, T? value, int startIndex, int count)
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal sealed class ObjectEqualityComparer<T> : EqualityComparer<T>
{
- [Pure]
public override bool Equals(T x, T y)
{
if (x != null)
return true;
}
- [Pure]
public override int GetHashCode(T obj) => obj?.GetHashCode() ?? 0;
internal override int IndexOf(T[] array, T value, int startIndex, int count)
}
}
- [Pure]
public override int GetHashCode(string obj)
{
if (obj == null) return 0;
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal sealed class ByteEqualityComparer : EqualityComparer<byte>
{
- [Pure]
public override bool Equals(byte x, byte y)
{
return x == y;
}
- [Pure]
public override int GetHashCode(byte b)
{
return b.GetHashCode();
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)
{
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal class EnumEqualityComparer<T> : EqualityComparer<T>, ISerializable where T : struct
{
- [Pure]
public override bool Equals(T x, T y)
{
int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(x);
return x_final == y_final;
}
- [Pure]
public override int GetHashCode(T obj)
{
int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj);
// 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);
// 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);
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal sealed class LongEnumEqualityComparer<T> : EqualityComparer<T>, ISerializable where T : struct
{
- [Pure]
public override bool Equals(T x, T y)
{
long x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(x);
return x_final == y_final;
}
- [Pure]
public override int GetHashCode(T obj)
{
long x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(obj);
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;
{
throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
- Contract.EndContractBlock();
uint seed;
uint incr;
// 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;)
// 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;)
throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - arrayIndex < Count)
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
- Contract.EndContractBlock();
CopyEntries(array, 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;)
{
throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
- Contract.EndContractBlock();
uint seed;
uint incr;
{
throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
- Contract.EndContractBlock();
if (count >= loadsize)
{
expand();
{
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;
{
if (table == null)
throw new ArgumentNullException(nameof(table));
- Contract.EndContractBlock();
return new SyncHashtable(table);
}
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);
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);
{
throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
- Contract.EndContractBlock();
return _table.ContainsKey(key);
}
{
if (min < 0)
throw new ArgumentException(SR.Arg_HTCapacityOverflow);
- Contract.EndContractBlock();
for (int i = 0; i < primes.Length; i++)
{
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Collections.ObjectModel
{
{
throw new ArgumentNullException(nameof(dictionary));
}
- Contract.EndContractBlock();
m_dictionary = dictionary;
}
{
get
{
- Contract.Ensures(Contract.Result<KeyCollection>() != null);
if (m_keys == null)
{
m_keys = new KeyCollection(m_dictionary.Keys);
{
get
{
- Contract.Ensures(Contract.Result<ValueCollection>() != null);
if (m_values == null)
{
m_values = new ValueCollection(m_dictionary.Values);
// 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
{
get
{
- Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Utc);
// following code is tuned for speed. Don't change it without running benchmark.
long ticks = 0;
ticks = GetSystemTimeAsFileTime();
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Runtime.Serialization;
-using System.Diagnostics.Contracts;
+using System.Diagnostics;
namespace System
{
{
if (bits == null)
throw new ArgumentNullException(nameof(bits));
- Contract.EndContractBlock();
if (bits.Length == 4)
{
int f = bits[3];
{
if (scale > 28)
throw new ArgumentOutOfRangeException(nameof(scale), SR.ArgumentOutOfRange_DecimalScale);
- Contract.EndContractBlock();
this.lo = lo;
this.mid = mid;
this.hi = hi;
//
public override String ToString()
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDecimal(this, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDecimal(this, format, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDecimal(this, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format, IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDecimal(this, format, NumberFormatInfo.GetInstance(provider));
}
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);
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);
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode));
}
- Contract.EndContractBlock();
if (mode == MidpointRounding.ToEven)
{
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
[ClassInterface(ClassInterfaceType.AutoDual)]
[System.Runtime.InteropServices.ComVisible(true)]
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
if (method == null)
throw new ArgumentNullException(nameof(method));
- Contract.EndContractBlock();
RuntimeType rtTarget = target as RuntimeType;
if (rtTarget == null)
throw new ArgumentNullException(nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
- Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
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;
throw new ArgumentNullException(nameof(type));
if (method == null)
throw new ArgumentNullException(nameof(method));
- Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentNullException(nameof(type));
if (method == null)
throw new ArgumentNullException(nameof(method));
- Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
// Validate the parameters.
if (type == null)
throw new ArgumentNullException(nameof(type));
- Contract.EndContractBlock();
if (method.IsNullHandle())
throw new ArgumentNullException(nameof(method));
if (method == null)
throw new ArgumentNullException(nameof(method));
- Contract.EndContractBlock();
RuntimeMethodInfo rtMethod = method as RuntimeMethodInfo;
if (rtMethod == null)
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
-using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics
#endif
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
- Contract.EndContractBlock();
for (int i = fromInclusive; i < toExclusive; i++)
if (!predicate(i)) return false;
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;
#endif
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
- Contract.EndContractBlock();
for (int i = fromInclusive; i < toExclusive; i++)
if (predicate(i)) return true;
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;
{
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);
#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;
{
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...
break;
default:
- Contract.Assume(false, "Unreachable code");
+ Debug.Fail("Unreachable code");
resourceName = "AssumptionFailed";
break;
}
using System;
using System.Runtime.InteropServices;
-using System.Diagnostics.Contracts;
namespace System.Diagnostics
{
{
if (state < DebuggerBrowsableState.Never || state > DebuggerBrowsableState.RootHidden)
throw new ArgumentOutOfRangeException(nameof(state));
- Contract.EndContractBlock();
this.state = state;
}
{
throw new ArgumentNullException(nameof(type));
}
- Contract.EndContractBlock();
typeName = type.AssemblyQualifiedName;
}
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
targetName = value.AssemblyQualifiedName;
target = value;
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
targetName = value.AssemblyQualifiedName;
target = value;
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<string> eventSourceNameFilter = new Lazy<string>(() => CompatibilitySwitch.GetValueInternal("EventSourceFilter"));
public static EventListener InitializePersistentListener()
{
try{
-
if (!initializedPersistentListener && XplatEventLogger.IsEventSourceLoggingEnabled())
{
initializedPersistentListener = true;
using System.IO;
using System.Collections;
using System.Runtime.Versioning;
-using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics
{
if (name != null && name.Length == 0)
throw new ArgumentOutOfRangeException(nameof(Name), SR.Argument_StringZeroLength);
- Contract.EndContractBlock();
if ((name != null) && (parent != null))
{
using System;
using System.IO;
using System.Reflection;
-using System.Diagnostics.Contracts;
namespace System.Diagnostics
{
//
public virtual MethodBase GetMethod()
{
- Contract.Ensures(Contract.Result<MethodBase>() != null);
-
return method;
}
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
-using System.Diagnostics.Contracts;
namespace System.Diagnostics
{
if (skipFrames < 0)
throw new ArgumentOutOfRangeException(nameof(skipFrames),
SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
if (skipFrames < 0)
throw new ArgumentOutOfRangeException(nameof(skipFrames),
SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
{
if (e == null)
throw new ArgumentNullException(nameof(e));
- Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
{
if (e == null)
throw new ArgumentNullException(nameof(e));
- Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
if (skipFrames < 0)
throw new ArgumentOutOfRangeException(nameof(skipFrames),
SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
if (skipFrames < 0)
throw new ArgumentOutOfRangeException(nameof(skipFrames),
SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
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;
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)
// This class represents an empty variant
////////////////////////////////////////////////////////////////////////////////
-using System.Diagnostics.Contracts;
using System;
using System.Runtime.Serialization;
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.
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);
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);
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;
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
- Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
- Contract.Ensures(Contract.Result<Type>() != null);
- Contract.EndContractBlock();
return enumType.GetEnumUnderlyingType();
}
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
- Contract.Ensures(Contract.Result<Array>() != null);
- Contract.EndContractBlock();
return enumType.GetEnumValues();
}
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
- Contract.EndContractBlock();
return enumType.GetEnumName(value);
}
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
- Contract.Ensures(Contract.Result<String[]>() != null);
- Contract.EndContractBlock();
return enumType.GetEnumNames();
}
{
if (value == null)
throw new ArgumentNullException(nameof(value));
- Contract.EndContractBlock();
// Delegate rest of error checking to the other functions
TypeCode typeCode = Convert.GetTypeCode(value);
}
}
- [Pure]
public static bool IsDefined(Type enumType, Object value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
- Contract.EndContractBlock();
return enumType.IsEnumDefined(value);
}
if (format == null)
throw new ArgumentNullException(nameof(format));
- Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
if (this == null)
throw new NullReferenceException();
- Contract.EndContractBlock();
int ret = InternalCompareTo(this, target);
{
if (flag == null)
throw new ArgumentNullException(nameof(flag));
- Contract.EndContractBlock();
if (!this.GetType().IsEquivalentTo(flag.GetType()))
{
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));
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));
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));
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));
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));
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));
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));
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));
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));
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));
using System.Threading;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
public enum EnvironmentVariableTarget
{
{
if (name == null)
throw new ArgumentNullException(nameof(name));
- Contract.EndContractBlock();
if (name.Length == 0)
{
{
get
{
- Contract.Ensures(Contract.Result<String>() != null);
#if PLATFORM_WINDOWS
return "\r\n";
#else
[MethodImpl(MethodImplOptions.NoInlining)] // Prevent inlining from affecting where the stacktrace starts
get
{
- Contract.Ensures(Contract.Result<String>() != null);
return Internal.Runtime.Augments.EnvironmentAugments.StackTrace;
}
}
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")]
{
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)
{
throw new ArgumentNullException(nameof(info));
}
- Contract.EndContractBlock();
String tempStackTraceString = _stackTraceString;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
-using System.Diagnostics.Contracts;
namespace System
{
throw new ArgumentOutOfRangeException("pressure",
SR.ArgumentOutOfRange_MustBeNonNegInt32);
}
- Contract.EndContractBlock();
_AddMemoryPressure((ulong)bytesAllocated);
}
throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
SR.ArgumentOutOfRange_MustBeNonNegInt32);
}
- Contract.EndContractBlock();
_RemoveMemoryPressure((ulong)bytesAllocated);
}
throw new ArgumentOutOfRangeException(nameof(mode), SR.ArgumentOutOfRange_Enum);
}
- Contract.EndContractBlock();
int iInternalModes = 0;
{
throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive);
}
- Contract.EndContractBlock();
return _CollectionCount(generation, 0);
}
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
- Contract.EndContractBlock();
_SuppressFinalize(obj);
}
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
- Contract.EndContractBlock();
_ReRegisterForFinalize(obj);
}
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
-using System.Diagnostics.Contracts;
using System.Collections.Generic;
namespace System.Globalization
////////////////////////////////////////////////////////////////////////////
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Globalization
{
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
}
- Contract.EndContractBlock();
return (InternalGetNumericValue(InternalConvertToUtf32(s, index)));
}
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
}
- Contract.EndContractBlock();
return (sbyte)(InternalGetDigitValues(InternalConvertToUtf32(s, index)) >> 8);
}
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
}
- Contract.EndContractBlock();
return (sbyte)(InternalGetDigitValues(InternalConvertToUtf32(s, index)) & 0x00FF);
}
{
throw new ArgumentOutOfRangeException(nameof(index));
}
- Contract.EndContractBlock();
return InternalGetUnicodeCategory(s, index);
}
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Globalization
{
private unsafe SortKey InvariantCreateSortKey(string source, CompareOptions options)
{
if (source == null) { throw new ArgumentNullException(nameof(source)); }
- Contract.EndContractBlock();
if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
{
// 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;
Debug.Assert(!_invariantMode);
if (source==null) { throw new ArgumentNullException(nameof(source)); }
- Contract.EndContractBlock();
if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
{
using System.Security;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
Debug.Assert(!_invariantMode);
if (source == null) { throw new ArgumentNullException(nameof(source)); }
- Contract.EndContractBlock();
if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
{
using System.Reflection;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Globalization
{
throw new ArgumentException(SR.Argument_OnlyMscorlib);
}
- Contract.EndContractBlock();
return GetCompareInfo(culture);
}
{
throw new ArgumentNullException(name == null ? nameof(name) : nameof(assembly));
}
- Contract.EndContractBlock();
if (assembly != typeof(Object).Module.Assembly)
{
{
throw new ArgumentNullException(nameof(name));
}
- Contract.EndContractBlock();
return CultureInfo.GetCultureInfo(name).CompareInfo;
}
{
// 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 -----/////////////////////////////////
throw new ArgumentNullException((source == null ? nameof(source) : nameof(prefix)),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
if (prefix.Length == 0)
{
throw new ArgumentNullException((source == null ? nameof(source) : nameof(suffix)),
SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
if (suffix.Length == 0)
{
{
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, CompareOptions.None);
}
{
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, CompareOptions.None);
}
{
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, options);
}
{
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, options);
}
{
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
}
{
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
}
{
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
}
{
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
}
if (count < 0 || startIndex > source.Length - count)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
- Contract.EndContractBlock();
if (options == CompareOptions.OrdinalIgnoreCase)
{
{
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.
{
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);
{
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,
{
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,
{
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);
// Verify Arguments
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
// Validate CompareOptions
// Ordinal can't be selected with other flags
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
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
- Contract.EndContractBlock();
return GetHashCodeOfStringCore(source, options);
}
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
using System.Threading;
{
throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum);
}
- Contract.EndContractBlock();
InitializeFromCultureId(culture, useUserOverride);
}
{
throw new ArgumentNullException(nameof(cultureName),SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
_cultureData = CultureData.GetCultureData(cultureName, false);
if (_cultureData == null)
//
public static CultureInfo CreateSpecificCulture(String name)
{
- Contract.Ensures(Contract.Result<CultureInfo>() != null);
-
CultureInfo culture;
try
{
get
{
- Contract.Ensures(Contract.Result<CultureInfo>() != null);
if (s_userDefaultCulture == null)
{
Init();
public static CultureInfo[] GetCultures(CultureTypes types)
{
- Contract.Ensures(Contract.Result<CultureInfo[]>() != null);
// internally we treat UserCustomCultures as Supplementals but v2
// treats as Supplementals and Replacements
if ((types & CultureTypes.UserCustomCulture) == CultureTypes.UserCustomCulture)
{
get
{
- Contract.Ensures(Contract.Result<string>() != null);
-
// special case the compatibility cultures
switch (this.Name)
{
{
get
{
- Contract.Ensures(Contract.Result<String>() != null);
Debug.Assert(_name != null, "[CultureInfo.DisplayName] Always expect _name to be set");
return _cultureData.SLOCALIZEDDISPLAYNAME;
{
get
{
- Contract.Ensures(Contract.Result<String>() != null);
return (_cultureData.SNATIVEDISPLAYNAME);
}
}
{
get
{
- Contract.Ensures(Contract.Result<String>() != null);
return (_cultureData.SENGDISPLAYNAME);
}
}
{
get
{
- Contract.Ensures(Contract.Result<String>() != null);
return (_cultureData.SISO639LANGNAME);
}
}
{
get
{
- Contract.Ensures(Contract.Result<String>() != null);
return _cultureData.SISO639LANGNAME2;
}
}
{
get
{
- Contract.Ensures(Contract.Result<String>() != null);
return _cultureData.SABBREVLANGNAME;
}
}
{
get
{
- Contract.Ensures(Contract.Result<Calendar[]>() != null);
-
//
// This property always returns a new copy of the calendar array.
//
public CultureInfo GetConsoleFallbackUICulture()
{
- Contract.Ensures(Contract.Result<CultureInfo>() != null);
-
CultureInfo temp = _consoleFallbackCulture;
if (temp == null)
{
{
throw new ArgumentNullException(nameof(ci));
}
- Contract.Ensures(Contract.Result<CultureInfo>() != null);
- Contract.EndContractBlock();
if (ci.IsReadOnly)
{
{
throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum);
}
- Contract.Ensures(Contract.Result<CultureInfo>() != null);
- Contract.EndContractBlock();
CultureInfo retval = GetCultureInfoHelper(culture, null, null);
if (null == retval)
{
throw new ArgumentNullException(nameof(altName));
}
- Contract.Ensures(Contract.Result<CultureInfo>() != null);
- Contract.EndContractBlock();
CultureInfo retval = GetCultureInfoHelper(-1, name, altName);
if (retval == null)
// This function is deprecated, we don't like it
public static CultureInfo GetCultureInfoByIetfLanguageTag(string name)
{
- Contract.Ensures(Contract.Result<CultureInfo>() != null);
-
// Disallow old zh-CHT/zh-CHS names
if (name == "zh-CHT" || name == "zh-CHS")
{
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Text;
namespace System.Globalization
{
throw new ArgumentNullException(nameof(name));
}
- Contract.EndContractBlock();
ushort codePage;
if (s_encodingDataTable.TryGetValue(name, out codePage))
using System.Runtime.Versioning;
using System.Security;
using System.Threading;
-using System.Diagnostics.Contracts;
namespace System.Globalization
{
{
throw new ArgumentNullException(nameof(name));
}
- Contract.EndContractBlock();
Object codePageObj;
// 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
{
if (unicode == null)
throw new ArgumentNullException(nameof(unicode));
- Contract.EndContractBlock();
return GetAscii(unicode, index, unicode.Length - index);
}
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)
{
{
if (ascii == null)
throw new ArgumentNullException(nameof(ascii));
- Contract.EndContractBlock();
return GetUnicode(ascii, index, ascii.Length - index);
}
// 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)
{
{
// 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;
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)
////////////////////////////////////////////////////////////////////////////
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Globalization
throw new ArgumentException(SR.Argument_NoRegionInvariantCulture, nameof(name));
}
- Contract.EndContractBlock();
//
// For CoreCLR we only want the region names that are full culture names
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Security;
using System.Text;
////////////////////////////////////////////////////////////////////////////
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
using System.Text;
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());
{
throw new ArgumentNullException(nameof(str));
}
- Contract.EndContractBlock();
if (str.Length == 0)
{
return (str);
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>() != Guid.Empty);
-
Guid guid;
Marshal.ThrowExceptionForHR(Win32Native.CoCreateGuid(out guid), new IntPtr(-1));
return guid;
using System.Text;
using System.Globalization;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Security;
namespace System.IO
}
if (!input.CanRead)
throw new ArgumentException(SR.Argument_StreamNotReadable);
- Contract.EndContractBlock();
_stream = input;
_decoder = encoding.GetDecoder();
_maxCharsSize = encoding.GetMaxCharCount(MaxCharBytesSize);
public virtual int PeekChar()
{
- Contract.Ensures(Contract.Result<int>() >= -1);
-
if (_stream == null) __Error.FileNotOpen();
if (!_stream.CanSeek)
public virtual int Read()
{
- Contract.Ensures(Contract.Result<int>() >= -1);
-
if (_stream == null)
{
__Error.FileNotOpen();
public virtual String ReadString()
{
- Contract.Ensures(Contract.Result<String>() != null);
-
if (_stream == null)
__Error.FileNotOpen();
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() <= count);
- Contract.EndContractBlock();
if (_stream == null)
__Error.FileNotOpen();
public virtual int Read(Span<char> destination)
{
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() <= destination.Length);
- Contract.EndContractBlock();
-
if (_stream == null)
__Error.FileNotOpen();
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- Contract.Ensures(Contract.Result<char[]>() != null);
- Contract.Ensures(Contract.Result<char[]>().Length <= count);
- Contract.EndContractBlock();
if (_stream == null)
{
__Error.FileNotOpen();
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() <= count);
- Contract.EndContractBlock();
if (_stream == null) __Error.FileNotOpen();
return _stream.Read(buffer, index, count);
public virtual int Read(Span<byte> destination)
{
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() <= destination.Length);
- Contract.EndContractBlock();
-
if (_stream == null)
__Error.FileNotOpen();
public virtual byte[] ReadBytes(int count)
{
if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.Ensures(Contract.Result<byte[]>() != null);
- Contract.Ensures(Contract.Result<byte[]>().Length <= Contract.OldValue(count));
- Contract.EndContractBlock();
if (_stream == null) __Error.FileNotOpen();
if (count == 0)
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.IO
{
{
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;
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
- Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
- Contract.EndContractBlock();
return InternalEnumerateFiles(path, searchPattern, searchOption);
}
private static IEnumerable<String> 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<IEnumerable<String>>() != null);
+ Debug.Assert(path != null);
+ Debug.Assert(searchPattern != null);
+ Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return EnumerateFileSystemNames(path, searchPattern, searchOption, true, false);
}
private static IEnumerable<String> 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<IEnumerable<String>>() != 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);
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.IO
{
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<String> lines = new List<String>();
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Threading;
namespace System.IO
internal static IEnumerable<String> 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<String> handler = new StringResultHandler(includeFiles, includeDirs);
return new FileSystemEnumerableIterator<String>(path, originalUserPath, searchPattern, searchOption, handler, checkHost);
#endif
internal FileSystemEnumerableIterator(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler<TSource> 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);
private void AddSearchableDirsToStack(Directory.SearchData localSearchData)
{
- Contract.Requires(localSearchData != null);
+ Debug.Assert(localSearchData != null);
String searchPath = Path.Combine(localSearchData.fullPath, "*");
SafeFindHandle hnd = null;
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("."))
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];
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);
internal abstract class SearchResultHandler<TSource>
{
-
internal abstract bool IsResultIncluded(SearchResult result);
internal abstract TSource CreateObject(SearchResult result);
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;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
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
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity);
}
- Contract.EndContractBlock();
_buffer = capacity != 0 ? new byte[capacity] : Array.Empty<byte>();
_capacity = capacity;
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;
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;
public override bool CanRead
{
- [Pure]
get { return _isOpen; }
}
public override bool CanSeek
{
- [Pure]
get { return _isOpen; }
}
public override bool CanWrite
{
- [Pure]
get { return _writable; }
}
// 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();
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.Ensures(Position == value);
- Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
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();
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)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
}
- Contract.Ensures(_length - _origin == value);
- Contract.EndContractBlock();
EnsureWriteable();
// Origin wasn't publicly exposed above.
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();
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)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream);
- Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
stream.Write(_buffer, _origin, _length - _origin);
using System.Runtime.ExceptionServices;
using System.Security;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Reflection;
namespace System.IO
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;
public abstract bool CanWrite
{
- [Pure]
get;
}
{
get
{
- Contract.Ensures(Contract.Result<int>() >= 0);
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
set
{
get
{
- Contract.Ensures(Contract.Result<int>() >= 0);
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
set
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<byte>.Shared.Rent(bufferSize);
bufferSize = 0; // reuse same field for high water mark to avoid needing another field in the state machine
// 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);
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();
}
[Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")]
protected virtual WaitHandle CreateWaitHandle()
{
- Contract.Ensures(Contract.Result<WaitHandle>() != null);
return new ManualResetEvent(false);
}
public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
- Contract.Ensures(Contract.Result<IAsyncResult>() != null);
return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
}
byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
bool serializeAsynchronously, bool apm)
{
- Contract.Ensures(Contract.Result<IAsyncResult>() != null);
if (!CanRead) __Error.ReadNotSupported();
// To avoid a race with a stream's position pointer & generating race conditions
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.EndContractBlock();
var readTask = _activeReadWriteTask;
public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
- Contract.Ensures(Contract.Result<IAsyncResult>() != null);
return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
}
byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
bool serializeAsynchronously, bool apm)
{
- Contract.Ensures(Contract.Result<IAsyncResult>() != null);
if (!CanWrite) __Error.WriteNotSupported();
// To avoid a race condition with a stream's position pointer & generating conditions
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)
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.
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
- Contract.EndContractBlock();
var writeTask = _activeReadWriteTask;
if (writeTask == null)
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;
// significantly for people who are reading one byte at a time.
public virtual int ReadByte()
{
- Contract.Ensures(Contract.Result<int>() >= -1);
- Contract.Ensures(Contract.Result<int>() < 256);
-
byte[] oneByteArray = new byte[1];
int r = Read(oneByteArray, 0, 1);
if (r == 0)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
- Contract.Ensures(Contract.Result<Stream>() != null);
- Contract.EndContractBlock();
if (stream is SyncStream)
return stream;
internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
- Contract.Ensures(Contract.Result<IAsyncResult>() != 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
internal static int BlockingEndRead(IAsyncResult asyncResult)
{
- Contract.Ensures(Contract.Result<int>() >= 0);
-
return SynchronousAsyncResult.EndRead(asyncResult);
}
internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
- Contract.Ensures(Contract.Result<IAsyncResult>() != 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
public override bool CanRead
{
- [Pure]
get { return true; }
}
public override bool CanWrite
{
- [Pure]
get { return true; }
}
public override bool CanSeek
{
- [Pure]
get { return true; }
}
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
- Contract.EndContractBlock();
return BlockingEndRead(asyncResult);
}
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
- Contract.EndContractBlock();
BlockingEndWrite(asyncResult);
}
{
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;
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.EndContractBlock();
lock (_stream)
return _stream.EndRead(asyncResult);
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
- Contract.EndContractBlock();
lock (_stream)
_stream.EndWrite(asyncResult);
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Threading.Tasks;
namespace System.IO
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);
}
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);
}
}
- [Pure]
public override int Peek() {
if (stream == null)
__Error.ReaderClosed();
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();
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();
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.
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.
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;
}
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;
// 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() {}
//
// This default method simply returns -1.
//
- [Pure]
public virtual int Peek()
{
- Contract.Ensures(Contract.Result<int>() >= -1);
-
return -1;
}
//
public virtual int Read()
{
- Contract.Ensures(Contract.Result<int>() >= -1);
return -1;
}
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(count));
- Contract.EndContractBlock();
int n = 0;
do {
// TextReader, and returns them as one string.
public virtual String ReadToEnd()
{
- Contract.Ensures(Contract.Result<String>() != null);
-
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
//
public virtual int ReadBlock([In, Out] char[] buffer, int index, int count)
{
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() <= count);
-
int i, n = 0;
do {
n += (i = Read(buffer, index + n, count - n));
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<int> 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<TextReader, char[], int, int>(this, buffer, index, count);
return Task<int>.Factory.StartNew(state =>
if (buffer.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
- Contract.EndContractBlock();
return ReadBlockAsyncInternal(buffer, index, count);
}
private async Task<int> 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
{
if (reader==null)
throw new ArgumentNullException(nameof(reader));
- Contract.Ensures(Contract.Result<TextReader>() != null);
- Contract.EndContractBlock();
if (reader is SyncTextReader)
return reader;
{
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;
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)
{
if (buffer.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
- Contract.EndContractBlock();
return Task.FromResult(ReadBlock(buffer, index, 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));
}
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.IO
{
{
private SafeBuffer _buffer;
private Int64 _offset;
- [ContractPublicPropertyName("Capacity")]
private Int64 _capacity;
private FileAccess _access;
private bool _isOpen;
{
throw new ArgumentOutOfRangeException(nameof(access));
}
- Contract.EndContractBlock();
if (_isOpen)
{
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- Contract.EndContractBlock();
if (!_isOpen)
{
{
throw new ArgumentException(SR.Argument_OffsetAndLengthOutOfBounds);
}
- Contract.EndContractBlock();
if (!CanRead)
{
if (!_isOpen)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- Contract.EndContractBlock();
if (!_isOpen)
{
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
- Contract.EndContractBlock();
if (!_isOpen)
{
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- Contract.EndContractBlock();
if (position > _capacity - sizeOfType)
{
if (position >= _capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- Contract.EndContractBlock();
if (position > _capacity - sizeOfType)
{
if (position >= _capacity)
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()
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")]
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);
{
throw new ArgumentNullException(nameof(info));
}
- Contract.EndContractBlock();
#if BIT64
info.AddValue("value", (long)(_value));
#else // !BIT64 (32)
public unsafe String ToString(String format)
{
- Contract.Ensures(Contract.Result<String>() != null);
-
#if BIT64
return ((long)_value).ToString(format, CultureInfo.InvariantCulture);
#else // !BIT64 (32)
public static int Size
{
- [Pure]
[System.Runtime.Versioning.NonVersionable]
get
{
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Runtime.Versioning;
-using System.Diagnostics.Contracts;
namespace System
{
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Reflection.Emit;
namespace System
// This method returns the Invocation list of this multicast delegate.
public override sealed Delegate[] GetInvocationList()
{
- Contract.Ensures(Contract.Result<Delegate[]>() != null);
-
Delegate[] del;
Object[] invocationList = _invocationList as Object[];
if (invocationList == null)
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Security;
-using System.Diagnostics.Contracts;
namespace System
{
{
throw new ArgumentNullException(nameof(nullableType));
}
- Contract.EndContractBlock();
Type result = null;
if (nullableType.IsGenericType && !nullableType.IsGenericTypeDefinition)
{
using System.Security;
using System.Text;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System
{
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;
// Returns a Type object which represent this object instance.
//
- [Pure]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Type GetType();
//
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);
//
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);
//
private FieldInfo GetFieldInfo(String typeName, String fieldName)
{
- Contract.Requires(typeName != null);
- Contract.Requires(fieldName != null);
- Contract.Ensures(Contract.Result<FieldInfo>() != null);
+ Debug.Assert(typeName != null);
+ Debug.Assert(fieldName != null);
Type t = GetType();
while (null != t)
using System.Configuration.Assemblies;
using StackCrawlMark = System.Threading.StackCrawlMark;
using System.Runtime.Serialization;
-using System.Diagnostics.Contracts;
using System.Runtime.Loader;
namespace System.Reflection
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Assembly Load(String assemblyString)
{
- Contract.Ensures(Contract.Result<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RuntimeAssembly.InternalLoad(assemblyString, ref stackMark);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Assembly Load(AssemblyName assemblyRef)
{
- Contract.Ensures(Contract.Result<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-
AssemblyName modifiedAssemblyRef = null;
if (assemblyRef != null && assemblyRef.CodeBase != null)
{
[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<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-
AssemblyName modifiedAssemblyRef = null;
if (assemblyRef != null && assemblyRef.CodeBase != null)
{
public static Assembly Load(byte[] rawAssembly,
byte[] rawSymbolStore)
{
- Contract.Ensures(Contract.Result<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-
AppDomain.CheckLoadByteArraySupported();
if (rawAssembly == null)
public static Assembly LoadFile(String path)
{
- Contract.Ensures(Contract.Result<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-
AppDomain.CheckLoadFileSupported();
Assembly result = null;
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
{
if (assemblyFile == null)
throw new ArgumentNullException(nameof(assemblyFile));
- Contract.EndContractBlock();
// Assembly.GetNameInternal() will not demand path discovery
// permission, so do that first.
{
if (assemblyName == null)
throw new ArgumentNullException(nameof(assemblyName));
- Contract.EndContractBlock();
if ((assemblyName.Length == 0) ||
(assemblyName[0] == '\0'))
throw new ArgumentException(SR.Format_StringZeroLength);
using System;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Reflection
{
using System.Security;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
-using System.Diagnostics.Contracts;
namespace System.Reflection
{
{
if (target == null)
throw new ArgumentNullException(nameof(target));
- Contract.EndContractBlock();
return target.GetCustomAttributesData();
}
{
if (target == null)
throw new ArgumentNullException(nameof(target));
- Contract.EndContractBlock();
return target.GetCustomAttributesData();
}
{
if (target == null)
throw new ArgumentNullException(nameof(target));
- Contract.EndContractBlock();
return target.GetCustomAttributesData();
}
{
if (customAttributeModule == null)
throw new ArgumentNullException(nameof(customAttributeModule));
- Contract.EndContractBlock();
Debug.Assert(customAttributeCtorParameters != null);
Debug.Assert(customAttributeNamedParameters != null);
{
if (argumentName == null)
throw new ArgumentNullException(nameof(argumentName));
- Contract.EndContractBlock();
m_argumentName = argumentName;
m_fieldOrProperty = fieldOrProperty;
#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;
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;
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;
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;
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;
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;
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;
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;
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;
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<Object>() : CreateAttributeArrayHelper(caType, 0);
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;
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);
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);
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);
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);
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);
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);
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);
{
if (decoratedModule.Assembly.ReflectionOnly)
throw new InvalidOperationException(SR.Arg_ReflectionOnlyCA);
- Contract.EndContractBlock();
CustomAttributeRecord[] car = CustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedMetadataToken);
{
if (decoratedModule.Assembly.ReflectionOnly)
throw new InvalidOperationException(SR.Arg_ReflectionOnlyCA);
- Contract.EndContractBlock();
MetadataImport scope = decoratedModule.MetadataImport;
CustomAttributeRecord[] car = CustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedMetadataToken);
#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;
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;
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;
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;
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;
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);
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;
internal ModuleBuilder GetModuleBuilder(InternalModuleBuilder module)
{
- Contract.Requires(module != null);
+ Debug.Assert(module != null);
Debug.Assert(this.InternalAssembly == module.Assembly);
lock (SyncRoot)
AssemblyName name,
AssemblyBuilderAccess access)
{
- Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
-
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalDefineDynamicAssembly(name, access,
ref stackMark, null);
AssemblyBuilderAccess access,
IEnumerable<CustomAttributeBuilder> assemblyAttributes)
{
- Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
-
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalDefineDynamicAssembly(name,
access,
public ModuleBuilder DefineDynamicModule(
String name)
{
- Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
-
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return DefineDynamicModuleInternal(name, false, ref stackMark);
}
String name,
bool emitSymbolInfo) // specify if emit symbol info or not
{
- Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
-
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return DefineDynamicModuleInternal(name, emitSymbolInfo, ref stackMark);
}
throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
if (name[0] == '\0')
throw new ArgumentException(SR.Argument_InvalidName, nameof(name));
- Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
- Contract.EndContractBlock();
BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.DefineDynamicModule( " + name + " )");
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;
throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
throw new ArgumentNullException(nameof(binaryAttribute));
- Contract.EndContractBlock();
lock (SyncRoot)
{
{
throw new ArgumentNullException(nameof(customBuilder));
}
- Contract.EndContractBlock();
lock (SyncRoot)
{
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
using System.Diagnostics.SymbolStore;
using System.Security;
using System.Runtime.InteropServices;
- using System.Diagnostics.Contracts;
public sealed class ConstructorBuilder : ConstructorInfo
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
- [Pure]
public override ParameterInfo[] GetParameters()
{
ConstructorInfo rci = GetTypeBuilder().GetConstructor(m_methodBuilder.m_parameterTypes);
using System.Runtime.InteropServices;
using System.Globalization;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Reflection.Emit
{
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)
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
- using System.Diagnostics.Contracts;
using System.Security;
internal class DynamicILGenerator : ILGenerator
LocalBuilder localBuilder;
if (localType == null)
throw new ArgumentNullException(nameof(localType));
- Contract.EndContractBlock();
RuntimeType rtType = localType as RuntimeType;
{
if (meth == null)
throw new ArgumentNullException(nameof(meth));
- Contract.EndContractBlock();
int stackchange = 0;
int token = 0;
{
if (con == null)
throw new ArgumentNullException(nameof(con));
- Contract.EndContractBlock();
RuntimeConstructorInfo rtConstructor = con as RuntimeConstructorInfo;
if (rtConstructor == null)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
- Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
{
if (field == null)
throw new ArgumentNullException(nameof(field));
- Contract.EndContractBlock();
RuntimeFieldInfo runtimeField = field as RuntimeFieldInfo;
if (runtimeField == null)
{
if (str == null)
throw new ArgumentNullException(nameof(str));
- Contract.EndContractBlock();
int tempVal = GetTokenForString(str);
EnsureCapacity(7);
if (methodInfo.DeclaringType != null && methodInfo.DeclaringType.ContainsGenericParameters)
throw new ArgumentException(SR.Argument_GenericsInvalid, nameof(methodInfo));
- Contract.EndContractBlock();
int tk;
int stackchange = 0;
{
if (signature == null)
throw new ArgumentNullException(nameof(signature));
- Contract.EndContractBlock();
int stackchange = 0;
EnsureCapacity(7);
{
if (CurrExcStackCount == 0)
throw new NotSupportedException(SR.Argument_NotInExceptionBlock);
- Contract.EndContractBlock();
__ExceptionInfo current = CurrExcStack[CurrExcStackCount - 1];
// 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,
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
public sealed class DynamicMethod : MethodInfo
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)
public override MethodInfo GetBaseDefinition() { return this; }
- [Pure]
public override ParameterInfo[] GetParameters() { return m_dynMethod.GetParameters(); }
public override MethodImplAttributes GetMethodImplementationFlags() { return m_dynMethod.GetMethodImplementationFlags(); }
{
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
return this;
}
- [Pure]
public override ParameterInfo[] GetParameters()
{
ParameterInfo[] privateParameters = LoadParameters();
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute)))
return new Object[] { new MethodImplAttribute((MethodImplOptions)GetMethodImplementationFlags()) };
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute)))
return true;
{
using System;
using System.Diagnostics.CodeAnalysis;
- using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.InteropServices;
using CultureInfo = System.Globalization.CultureInfo;
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()
{
using System;
using System.Reflection;
using System.Runtime.InteropServices;
-using System.Diagnostics.Contracts;
namespace System.Reflection.Emit
{
{
throw new ArgumentNullException(nameof(mdBuilder));
}
- Contract.EndContractBlock();
m_type.ThrowIfCreated();
TypeBuilder.DefineMethodSemantics(
throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
throw new ArgumentNullException(nameof(binaryAttribute));
- Contract.EndContractBlock();
m_type.ThrowIfCreated();
TypeBuilder.DefineCustomAttribute(
{
throw new ArgumentNullException(nameof(customBuilder));
}
- Contract.EndContractBlock();
m_type.ThrowIfCreated();
customBuilder.CreateCustomAttribute(m_module, m_evToken.Token);
}
using System;
using CultureInfo = System.Globalization.CultureInfo;
using System.Reflection;
- using System.Diagnostics.Contracts;
public sealed class FieldBuilder : FieldInfo
{
if (type == typeof(void))
throw new ArgumentException(SR.Argument_BadFieldType);
- Contract.EndContractBlock();
m_fieldName = fieldName;
m_typeBuilder = typeBuilder;
if (binaryAttribute == null)
throw new ArgumentNullException(nameof(binaryAttribute));
- Contract.EndContractBlock();
ModuleBuilder module = m_typeBuilder.Module as ModuleBuilder;
{
if (customBuilder == null)
throw new ArgumentNullException(nameof(customBuilder));
- Contract.EndContractBlock();
m_typeBuilder.ThrowIfCreated();
namespace System.Reflection.Emit
{
-
public enum FlowControl
{
Branch = 0,
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
-using System.Diagnostics.Contracts;
namespace System.Reflection.Emit
{
{
if (rank <= 0)
throw new IndexOutOfRangeException();
- Contract.EndContractBlock();
string szrank = "";
if (rank == 1)
public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); }
- [Pure]
public override bool IsSubclassOf(Type c) { throw new NotSupportedException(); }
#endregion
internal static T[] EnlargeArray<T>(T[] incoming, int requiredSize)
{
- Contract.Requires(incoming != null);
- Contract.Ensures(Contract.Result<T[]>() != null);
- Contract.Ensures(Contract.Result<T[]>().Length == requiredSize);
+ Debug.Assert(incoming != null);
T[] temp = new T[requiredSize];
Array.Copy(incoming, 0, temp, 0, incoming.Length);
private static byte[] EnlargeArray(byte[] incoming, int requiredSize)
{
- Contract.Requires(incoming != null);
- Contract.Ensures(Contract.Result<byte[]>() != null);
- Contract.Ensures(Contract.Result<byte[]>().Length == requiredSize);
+ Debug.Assert(incoming != null);
byte[] temp = new byte[requiredSize];
Buffer.BlockCopy(incoming, 0, temp, 0, incoming.Length);
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)
{
{
if (meth == null)
throw new ArgumentNullException(nameof(meth));
- Contract.EndContractBlock();
if (opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj))
{
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);
{
if (signature == null)
throw new ArgumentNullException(nameof(signature));
- Contract.EndContractBlock();
int stackchange = 0;
ModuleBuilder modBuilder = (ModuleBuilder)m_methodBuilder.Module;
{
if (con == null)
throw new ArgumentNullException(nameof(con));
- Contract.EndContractBlock();
int stackchange = 0;
{
if (labels == null)
throw new ArgumentNullException(nameof(labels));
- Contract.EndContractBlock();
// Emitting a switch table
{
throw new ArgumentNullException(nameof(local));
}
- Contract.EndContractBlock();
int tempVal = local.GetLocalIndex();
if (local.GetMethodBuilder() != m_methodBuilder)
{
{
throw new ArgumentException(SR.Argument_NotExceptionType);
}
- Contract.EndContractBlock();
ConstructorInfo con = excType.GetConstructor(Type.EmptyTypes);
if (con == null)
{
{
throw new ArgumentNullException(nameof(fld));
}
- Contract.EndContractBlock();
MethodInfo prop = GetConsoleType().GetMethod("get_Out");
Emit(OpCodes.Call, prop);
if (usingNamespace.Length == 0)
throw new ArgumentException(SR.Argument_EmptyName, nameof(usingNamespace));
- Contract.EndContractBlock();
int index;
MethodBuilder methodBuilder = m_methodBuilder as MethodBuilder;
{
throw new ArgumentOutOfRangeException(nameof(startLine));
}
- Contract.EndContractBlock();
m_LineNumberInfo.AddLineNumberInfo(document, m_length, startLine, startColumn, endLine, endColumn);
}
// 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");
{
throw new ArgumentException(SR.Argument_UnmatchingSymScope);
}
- Contract.EndContractBlock();
// make sure that arrays are large enough to hold addition info
EnsureCapacity();
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
public sealed class MethodBuilder : MethodInfo
{
if (mod == null)
throw new ArgumentNullException(nameof(mod));
- Contract.EndContractBlock();
if (parameterTypes != null)
{
{
throw new ArgumentNullException(nameof(il));
}
- Contract.EndContractBlock();
__ExceptionInfo[] excp;
int counter = 0;
}
}
- [Pure]
public override ParameterInfo[] GetParameters()
{
if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null)
if (names.Length == 0)
throw new ArgumentException(SR.Arg_EmptyArray, nameof(names));
- Contract.EndContractBlock();
if (m_inst != null)
throw new InvalidOperationException(SR.InvalidOperation_GenericParametersAlreadySet);
{
if (position < 0)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence);
- Contract.EndContractBlock();
ThrowIfGeneric();
m_containingType.ThrowIfCreated();
public ILGenerator GetILGenerator()
{
- Contract.Ensures(Contract.Result<ILGenerator>() != null);
-
ThrowIfGeneric();
ThrowIfShouldNotHaveBody();
public ILGenerator GetILGenerator(int size)
{
- Contract.Ensures(Contract.Result<ILGenerator>() != null);
-
ThrowIfGeneric();
ThrowIfShouldNotHaveBody();
throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
throw new ArgumentNullException(nameof(binaryAttribute));
- Contract.EndContractBlock();
ThrowIfGeneric();
{
if (customBuilder == null)
throw new ArgumentNullException(nameof(customBuilder));
- Contract.EndContractBlock();
ThrowIfGeneric();
using System.Reflection;
using System.Collections;
using System.Globalization;
-using System.Diagnostics.Contracts;
namespace System.Reflection.Emit
{
{
if (!method.IsGenericMethodDefinition)
throw new InvalidOperationException();
- Contract.EndContractBlock();
return new MethodBuilderInstantiation(method, inst);
}
#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); } }
using System.Runtime.Versioning;
using System.Runtime.CompilerServices;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
internal sealed class InternalModuleBuilder : RuntimeModule
{
if (con == null)
throw new ArgumentNullException(nameof(con));
- Contract.EndContractBlock();
int tr;
int mr = 0;
public override Assembly Assembly
{
- [Pure]
get
{
return m_assemblyBuilder;
#region Define Type
public TypeBuilder DefineType(String name)
{
- Contract.Ensures(Contract.Result<TypeBuilder>() != null);
-
lock (SyncRoot)
{
return DefineTypeNoLock(name, TypeAttributes.NotPublic, null, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
public TypeBuilder DefineType(String name, TypeAttributes attr)
{
- Contract.Ensures(Contract.Result<TypeBuilder>() != null);
-
lock (SyncRoot)
{
return DefineTypeNoLock(name, attr, null, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent)
{
- Contract.Ensures(Contract.Result<TypeBuilder>() != null);
-
lock (SyncRoot)
{
// Why do we only call CheckContext here? Why don't we call it in the other overloads?
public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, int typesize)
{
- Contract.Ensures(Contract.Result<TypeBuilder>() != null);
-
lock (SyncRoot)
{
return DefineTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, typesize);
public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize)
{
- Contract.Ensures(Contract.Result<TypeBuilder>() != null);
-
lock (SyncRoot)
{
return DefineTypeNoLock(name, attr, parent, null, packingSize, typesize);
public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, Type[] interfaces)
{
- Contract.Ensures(Contract.Result<TypeBuilder>() != null);
-
lock (SyncRoot)
{
return DefineTypeNoLock(name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
private TypeBuilder DefineTypeNoLock(String name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize)
{
- Contract.Ensures(Contract.Result<TypeBuilder>() != 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<TypeBuilder>() != null);
-
lock (SyncRoot)
{
return DefineTypeNoLock(name, attr, parent, packsize);
private TypeBuilder DefineTypeNoLock(String name, TypeAttributes attr, Type parent, PackingSize packsize)
{
- Contract.Ensures(Contract.Result<TypeBuilder>() != null);
-
return new TypeBuilder(name, attr, parent, null, this, packsize, TypeBuilder.UnspecifiedTypeSize, null);
}
// Nested enum types can be defined manually using ModuleBuilder.DefineType.
public EnumBuilder DefineEnum(String name, TypeAttributes visibility, Type underlyingType)
{
- Contract.Ensures(Contract.Result<EnumBuilder>() != null);
-
CheckContext(underlyingType);
lock (SyncRoot)
{
private EnumBuilder DefineEnumNoLock(String name, TypeAttributes visibility, Type underlyingType)
{
- Contract.Ensures(Contract.Result<EnumBuilder>() != null);
-
return new EnumBuilder(name, underlyingType, visibility, this);
}
#region Define Global Method
public MethodBuilder DefineGlobalMethod(String name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
{
- Contract.Ensures(Contract.Result<MethodBuilder>() != 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<MethodBuilder>() != null);
-
return DefineGlobalMethod(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
}
if ((attributes & MethodAttributes.Static) == 0)
throw new ArgumentException(SR.Argument_GlobalFunctionHasToBeStatic);
- Contract.Ensures(Contract.Result<MethodBuilder>() != null);
- Contract.EndContractBlock();
CheckContext(returnType);
CheckContext(requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes);
// 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<FieldBuilder>() != null);
lock (SyncRoot)
{
{
throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated);
}
- Contract.Ensures(Contract.Result<FieldBuilder>() != null);
- Contract.EndContractBlock();
m_moduleData.m_fHasGlobal = true;
return m_moduleData.m_globalTypeBuilder.DefineInitializedData(name, data, attributes);
public FieldBuilder DefineUninitializedData(String name, int size, FieldAttributes attributes)
{
- Contract.Ensures(Contract.Result<FieldBuilder>() != null);
-
lock (SyncRoot)
{
return DefineUninitializedDataNoLock(name, size, attributes);
{
throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated);
}
- Contract.Ensures(Contract.Result<FieldBuilder>() != null);
- Contract.EndContractBlock();
m_moduleData.m_fHasGlobal = true;
return m_moduleData.m_globalTypeBuilder.DefineUninitializedData(name, size, attributes);
{
if (type == null)
throw new ArgumentNullException(nameof(type));
- Contract.EndContractBlock();
CheckContext(type);
// return the MethodDef token.
if (method == null)
throw new ArgumentNullException(nameof(method));
- Contract.EndContractBlock();
int tr;
int mr = 0;
if (arrayClass.IsArray == false)
throw new ArgumentException(SR.Argument_HasToBeArrayClass);
- Contract.EndContractBlock();
CheckContext(returnType, arrayClass);
CheckContext(parameterTypes);
{
throw new ArgumentNullException(nameof(field));
}
- Contract.EndContractBlock();
int tr;
int mr = 0;
{
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.
{
throw new ArgumentNullException(nameof(sigHelper));
}
- Contract.EndContractBlock();
int sigLength;
byte[] sigBytes;
{
if (sigBytes == null)
throw new ArgumentNullException(nameof(sigBytes));
- Contract.EndContractBlock();
byte[] localSigBytes = new byte[sigBytes.Length];
Buffer.BlockCopy(sigBytes, 0, localSigBytes, 0, sigBytes.Length);
throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
throw new ArgumentNullException(nameof(binaryAttribute));
- Contract.EndContractBlock();
TypeBuilder.DefineCustomAttribute(
this,
{
throw new ArgumentNullException(nameof(customBuilder));
}
- Contract.EndContractBlock();
customBuilder.CreateCustomAttribute(this, 1); // This is hard coding the module token to 1
}
// url cannot be null but can be an empty string
if (url == null)
throw new ArgumentNullException(nameof(url));
- Contract.EndContractBlock();
lock (SyncRoot)
{
return m_iSymWriter.DefineDocument(url, language, languageVendor, documentType);
}
- [Pure]
public bool IsTransient()
{
return InternalModule.IsTransientInternal();
using System;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Reflection;
namespace System.Reflection.Emit
{
-
public enum OpCodeType
{
[Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
namespace System.Reflection.Emit
{
-
///<summary>
/// Internal enum OpCodeValues for opcode values.
///</summary>
/// <seealso topic='IL Instruction Set Specification'/>
public class OpCodes
{
-
private OpCodes()
{
}
using System;
using System.Threading;
-using System.Diagnostics.Contracts;
namespace System.Reflection.Emit
{
}
}
- [Pure]
public override bool Equals(Object obj)
{
if (obj is OpCode)
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);
namespace System.Reflection.Emit
{
-
public enum OperandType
{
InlineBrTarget = 0,
using System.Runtime.InteropServices;
using System;
using System.Reflection;
-using System.Diagnostics.Contracts;
namespace System.Reflection.Emit
{
throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
throw new ArgumentNullException(nameof(binaryAttribute));
- Contract.EndContractBlock();
TypeBuilder.DefineCustomAttribute(
m_methodBuilder.GetModuleBuilder(),
{
throw new ArgumentNullException(nameof(customBuilder));
}
- Contract.EndContractBlock();
customBuilder.CreateCustomAttribute((ModuleBuilder)(m_methodBuilder.GetModule()), m_pdToken.Token);
}
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
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;
using System.Text;
using System;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 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)
{
namespace System.Reflection.Emit
{
-
public enum StackBehaviour
{
Pop0 = 0,
using System.Runtime.InteropServices;
using System;
using System.Reflection;
- using System.Diagnostics.Contracts;
using CultureInfo = System.Globalization.CultureInfo;
internal sealed class SymbolMethod : MethodInfo
#endregion
#region MethodBase Overrides
- [Pure]
public override ParameterInfo[] GetParameters()
{
throw new NotSupportedException(SR.NotSupported_SymbolMethod);
using System.Runtime.InteropServices;
using System;
using System.Reflection;
- using System.Diagnostics.Contracts;
using CultureInfo = System.Globalization.CultureInfo;
internal enum TypeKind
{
if (baseType == null)
throw new ArgumentNullException(nameof(baseType));
- Contract.EndContractBlock();
m_baseType = baseType;
}
{
if (rank <= 0)
throw new IndexOutOfRangeException();
- Contract.EndContractBlock();
string szrank = "";
if (rank == 1)
{
if (!IsArray)
throw new NotSupportedException(SR.NotSupported_SubclassOverride);
- Contract.EndContractBlock();
return m_cRank;
}
using System.Threading;
using System.Runtime.Versioning;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
public enum PackingSize
if (binaryAttribute == null)
throw new ArgumentNullException(nameof(binaryAttribute));
- Contract.EndContractBlock();
m_con = con;
m_binaryAttribute = binaryAttribute;
{
if (customBuilder == null)
throw new ArgumentNullException(nameof(customBuilder));
- Contract.EndContractBlock();
m_customBuilder = customBuilder;
}
if (type.GetGenericTypeDefinition() != method.DeclaringType)
throw new ArgumentException(SR.Argument_InvalidMethodDeclaringType, nameof(type));
- Contract.EndContractBlock();
// The following converts from Type or TypeBuilder of G<T> to TypeBuilderInstantiation G<T>. These types
// both logically represent the same thing. The runtime displays a similar convention by having
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));
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));
#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
// 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();
// 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);
if (fullname.Length > 1023)
throw new ArgumentException(SR.Argument_TypeNameTooLong, nameof(fullname));
- Contract.EndContractBlock();
int i;
m_module = module;
if (size <= 0 || size >= 0x003f0000)
throw new ArgumentException(SR.Argument_BadSizeForData);
- Contract.EndContractBlock();
ThrowIfCreated();
}
}
- [Pure]
public bool IsCreated()
{
return m_hasBeenCreated;
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
return m_bakedRuntimeType.GUID;
}
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
return m_bakedRuntimeType.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
}
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
return m_bakedRuntimeType.GetConstructor(bindingAttr, binder, callConvention, types, modifiers);
}
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
return m_bakedRuntimeType.GetConstructors(bindingAttr);
}
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
if (types == null)
{
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
return m_bakedRuntimeType.GetMethods(bindingAttr);
}
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
return m_bakedRuntimeType.GetField(name, bindingAttr);
}
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
return m_bakedRuntimeType.GetFields(bindingAttr);
}
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
return m_bakedRuntimeType.GetInterface(name, ignoreCase);
}
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
return m_bakedRuntimeType.GetEvent(name, bindingAttr);
}
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
return m_bakedRuntimeType.GetEvents();
}
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
return m_bakedRuntimeType.GetProperties(bindingAttr);
}
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
return m_bakedRuntimeType.GetNestedTypes(bindingAttr);
}
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
return m_bakedRuntimeType.GetNestedType(name, bindingAttr);
}
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
return m_bakedRuntimeType.GetMember(name, type, bindingAttr);
}
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
return m_bakedRuntimeType.GetInterfaceMap(interfaceType);
}
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
return m_bakedRuntimeType.GetEvents(bindingAttr);
}
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
return m_bakedRuntimeType.GetMembers(bindingAttr);
}
get { return false; }
}
- [Pure]
public override bool IsSubclassOf(Type c)
{
Type p = this;
{
if (rank <= 0)
throw new IndexOutOfRangeException();
- Contract.EndContractBlock();
string szrank = "";
if (rank == 1)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- Contract.EndContractBlock();
return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, typeof(object) as RuntimeType, inherit);
}
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (names.Length == 0)
throw new ArgumentException();
- Contract.EndContractBlock();
for (int i = 0; i < names.Length; i++)
if (names[i] == null)
if (methodInfoDeclaration == null)
throw new ArgumentNullException(nameof(methodInfoDeclaration));
- Contract.EndContractBlock();
ThrowIfCreated();
public MethodBuilder DefineMethod(String name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
{
- Contract.Ensures(Contract.Result<MethodBuilder>() != null);
-
return DefineMethod(name, attributes, CallingConventions.Standard, returnType, parameterTypes);
}
public MethodBuilder DefineMethod(String name, MethodAttributes attributes)
{
- Contract.Ensures(Contract.Result<MethodBuilder>() != null);
-
return DefineMethod(name, attributes, CallingConventions.Standard, null, null);
}
public MethodBuilder DefineMethod(String name, MethodAttributes attributes, CallingConventions callingConvention)
{
- Contract.Ensures(Contract.Result<MethodBuilder>() != 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<MethodBuilder>() != null);
-
return DefineMethod(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
}
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
{
- Contract.Ensures(Contract.Result<MethodBuilder>() != null);
-
lock (SyncRoot)
{
return DefineMethodNoLock(name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers,
if (name.Length == 0)
throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
- Contract.Ensures(Contract.Result<MethodBuilder>() != null);
- Contract.EndContractBlock();
CheckContext(returnType);
CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes);
{
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
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);
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;
{
throw new ArgumentNullException(nameof(interfaceType));
}
- Contract.EndContractBlock();
CheckContext(interfaceType);
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);
{
if (customBuilder == null)
throw new ArgumentNullException(nameof(customBuilder));
- Contract.EndContractBlock();
customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, m_tdType.Token);
}
using System.Reflection;
using System.Collections;
using System.Globalization;
-using System.Diagnostics.Contracts;
+using System.Diagnostics;
namespace System.Reflection.Emit
{
#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)
{
{
if (rank <= 0)
throw new IndexOutOfRangeException();
- Contract.EndContractBlock();
string comma = "";
for (int i = 1; i < rank; i++)
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();
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Reflection.Emit
{
#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; } }
{
if (!IsGenericMethodDefinition)
throw new InvalidOperationException(SR.Arg_NotGenericMethodDefinition);
- Contract.EndContractBlock();
return MethodBuilderInstantiation.MakeGenericMethod(this, typeArgs);
}
#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; } }
// See the LICENSE file in the project root for more information.
using System.Globalization;
-using System.Diagnostics.Contracts;
namespace System.Reflection
{
#region Private Data Members
private MethodBody m_methodBody;
- [ContractPublicPropertyName("Flags")]
private ExceptionHandlingClauseOptions m_flags;
private int m_tryOffset;
private int m_tryLength;
using System.Runtime.InteropServices;
using System.Configuration.Assemblies;
using System.Runtime.Versioning;
-using System.Diagnostics.Contracts;
namespace System.Reflection
{
{
if (index < 0 || index >= m_length)
throw new IndexOutOfRangeException();
- Contract.EndContractBlock();
unsafe
{
{
get
{
- Contract.Requires(0 <= index && index < Length);
+ Debug.Assert(0 <= index && index < Length);
if (largeResult != null)
return largeResult[index];
// 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;
{
if (obj.IsNull)
throw new ArgumentException(SR.Arg_TypedReference_Null);
- Contract.EndContractBlock();
unsafe
{
{
if (obj.IsNull)
throw new ArgumentException(SR.Arg_TypedReference_Null);
- Contract.EndContractBlock();
unsafe
{
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Threading;
-using System.Diagnostics.Contracts;
namespace System.Reflection
{
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
{
if (assemblyString == null)
throw new ArgumentNullException(nameof(assemblyString));
- Contract.EndContractBlock();
if ((assemblyString.Length == 0) ||
(assemblyString[0] == '\0'))
{
if (assemblyRef == null)
throw new ArgumentNullException(nameof(assemblyRef));
- Contract.EndContractBlock();
if (assemblyRef.CodeBase != null)
{
{
if (culture == null)
throw new ArgumentNullException(nameof(culture));
- Contract.EndContractBlock();
String name = GetSimpleName() + ".resources";
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Globalization;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
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;
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
return m_parameters;
}
- [Pure]
public override ParameterInfo[] GetParameters()
{
ParameterInfo[] parameters = GetParametersNoCopy();
{
if (declaringType == null)
throw new ArgumentNullException(nameof(declaringType));
- Contract.EndContractBlock();
// ctor is ReflectOnly
if (declaringType is ReflectionOnlyType)
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
}
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;
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
// 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
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Security;
using System.Text;
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));
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
return m_parameters;
}
- [System.Diagnostics.Contracts.Pure]
public override ParameterInfo[] GetParameters()
{
FetchNonReturnParameters();
{
get
{
- Contract.Ensures(m_returnParameter != null);
-
FetchReturnParameter();
return m_returnParameter as ParameterInfo;
}
// Validate the parameters.
if (delegateType == null)
throw new ArgumentNullException(nameof(delegateType));
- Contract.EndContractBlock();
RuntimeType rtType = delegateType as RuntimeType;
if (rtType == null)
{
if (methodInstantiation == null)
throw new ArgumentNullException(nameof(methodInstantiation));
- Contract.EndContractBlock();
RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length];
{
if (!IsGenericMethod)
throw new InvalidOperationException();
- Contract.EndContractBlock();
return RuntimeType.GetMethodBase(m_declaringType, RuntimeMethodHandle.StripMethodInstantiation(this)) as MethodInfo;
}
using System.Runtime.CompilerServices;
using System.Security;
using System.Globalization;
-using System.Diagnostics.Contracts;
namespace System.Reflection
{
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
public override Assembly Assembly
{
- [Pure]
get
{
return GetRuntimeAssembly();
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using MdToken = System.Reflection.MetadataToken;
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));
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)
{
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)
{
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
if (MdToken.IsNullToken(m_tkParamDef))
return Array.Empty<Object>();
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
if (MdToken.IsNullToken(m_tkParamDef))
return false;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Text;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
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;
// 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);
}
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
using System.Text;
using System.Threading;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
internal class FileBasedResourceGroveler : IResourceGroveler
{
using System.Text;
using System.Threading;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
using Microsoft.Win32;
//
{
// 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;
}
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.
[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)
using System.Collections.Generic;
using System.Runtime.Versioning;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
#if FEATURE_APPX
//
throw new ArgumentNullException(nameof(baseName));
if (null == resourceDir)
throw new ArgumentNullException(nameof(resourceDir));
- Contract.EndContractBlock();
BaseNameField = baseName;
if (null == assembly)
throw new ArgumentNullException(nameof(assembly));
- Contract.EndContractBlock();
if (!(assembly is RuntimeAssembly))
throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly);
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);
{
if (null == resourceSource)
throw new ArgumentNullException(nameof(resourceSource));
- Contract.EndContractBlock();
if (!(resourceSource is RuntimeType))
throw new ArgumentException(SR.Argument_MustBeRuntimeType);
{
if (null == culture)
throw new ArgumentNullException(nameof(culture));
- Contract.EndContractBlock();
Dictionary<String, ResourceSet> localResourceSets = _resourceSets;
ResourceSet rs;
{
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.
{
if (null == name)
throw new ArgumentNullException(nameof(name));
- Contract.EndContractBlock();
#if FEATURE_APPX
if (s_IsAppXModel)
{
if (null == name)
throw new ArgumentNullException(nameof(name));
- Contract.EndContractBlock();
#if FEATURE_APPX
if (s_IsAppXModel)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanRead)
throw new ArgumentException(SR.Argument_StreamNotReadable);
- Contract.EndContractBlock();
_resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default);
_store = new BinaryReader(stream, Encoding.UTF8);
// and values, coupled to this ResourceReader).
internal ResourceReader(Stream stream, Dictionary<String, ResourceLocator> 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);
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)
{
if (resourceName == null)
throw new ArgumentNullException(nameof(resourceName));
- Contract.EndContractBlock();
if (_resCache == null)
throw new InvalidOperationException(SR.ResourceReaderIsClosed);
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.");
using System.Collections;
using System.IO;
using System.Reflection;
-using System.Diagnostics.Contracts;
namespace System.Resources
{
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
- Contract.EndContractBlock();
Reader = reader;
CommonInit();
ReadResources();
{
if (name == null)
throw new ArgumentNullException(nameof(name));
- Contract.EndContractBlock();
Hashtable copyOfTable = Table; // Avoid a race with Dispose
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Resources
{
using DebuggerStepThroughAttribute = System.Diagnostics.DebuggerStepThroughAttribute;
using MdToken = System.Reflection.MetadataToken;
using System.Runtime.Versioning;
-using System.Diagnostics.Contracts;
namespace System
{
{
get
{
- Contract.Requires(index < Count);
+ Debug.Assert(index < Count);
return (_items != null) ? _items[index] : _item;
}
}
private unsafe void PopulateRtFields(Filter filter,
IntPtr* ppFieldHandles, int count, RuntimeType declaringType, ref ListBuilder<RuntimeFieldInfo> 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;
private unsafe void PopulateLiteralFields(Filter filter, RuntimeType declaringType, ref ListBuilder<RuntimeFieldInfo> list)
{
- Contract.Requires(declaringType != null);
- Contract.Requires(ReflectedType != null);
+ Debug.Assert(declaringType != null);
+ Debug.Assert(ReflectedType != null);
int tkDeclaringType = RuntimeTypeHandle.GetToken(declaringType);
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<String, RuntimeEventInfo> csEventInfos = filter.CaseSensitive() ? null :
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.
{
if (typeName == null)
throw new ArgumentNullException(nameof(typeName));
- Contract.EndContractBlock();
return RuntimeTypeHandle.GetTypeByName(
typeName, throwOnError, ignoreCase, reflectionOnly, ref stackMark, false);
return property;
}
- Contract.Assume(false, "Unreachable code");
+ Debug.Fail("Unreachable code");
throw new SystemException();
}
{
if (genericArguments == null)
throw new ArgumentNullException();
- Contract.EndContractBlock();
for (int i = 0; i < genericArguments.Length; i++)
{
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
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;
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;
if ((object)ifaceType == null)
throw new ArgumentNullException(nameof(ifaceType));
- Contract.EndContractBlock();
RuntimeType ifaceRtType = ifaceType as RuntimeType;
String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
{
if (name == null) throw new ArgumentNullException();
- Contract.EndContractBlock();
ListBuilder<PropertyInfo> candidates = GetPropertyCandidates(name, bindingAttr, types, false);
public override EventInfo GetEvent(String name, BindingFlags bindingAttr)
{
if (name == null) throw new ArgumentNullException();
- Contract.EndContractBlock();
bool ignoreCase;
MemberListType listType;
public override FieldInfo GetField(String name, BindingFlags bindingAttr)
{
if (name == null) throw new ArgumentNullException();
- Contract.EndContractBlock();
bool ignoreCase;
MemberListType listType;
public override Type GetInterface(String fullname, bool ignoreCase)
{
if (fullname == null) throw new ArgumentNullException();
- Contract.EndContractBlock();
BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic;
public override Type GetNestedType(String fullname, BindingFlags bindingAttr)
{
if (fullname == null) throw new ArgumentNullException();
- Contract.EndContractBlock();
bool ignoreCase;
bindingAttr &= ~BindingFlags.Static;
public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
{
if (name == null) throw new ArgumentNullException();
- Contract.EndContractBlock();
ListBuilder<MethodInfo> methods = new ListBuilder<MethodInfo>();
ListBuilder<ConstructorInfo> constructors = new ListBuilder<ConstructorInfo>();
{
if (!IsGenericParameter)
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
- Contract.EndContractBlock();
IRuntimeMethodInfo declaringMethod = RuntimeTypeHandle.GetDeclaringMethod(this);
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;
{
if (!IsGenericParameter)
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
- Contract.EndContractBlock();
GenericParameterAttributes attributes;
{
if (!IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, "enumType");
- Contract.EndContractBlock();
String[] ret = Enum.InternalGetNames(this);
{
if (!IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, "enumType");
- Contract.EndContractBlock();
// Get all of the values
ulong[] values = Enum.InternalGetValues(this);
{
if (!IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, "enumType");
- Contract.EndContractBlock();
return Enum.InternalGetUnderlyingType(this);
}
{
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();
{
if (value == null)
throw new ArgumentNullException(nameof(value));
- Contract.EndContractBlock();
Type valueType = value.GetType();
{
if (instantiation == null)
throw new ArgumentNullException(nameof(instantiation));
- Contract.EndContractBlock();
RuntimeType[] instantiationRuntimeType = new RuntimeType[instantiation.Length];
{
if (!IsGenericParameter)
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
- Contract.EndContractBlock();
return new RuntimeTypeHandle(this).GetGenericVariableIndex();
}
{
if (!IsGenericType)
throw new InvalidOperationException(SR.InvalidOperation_NotGenericType);
- Contract.EndContractBlock();
return RuntimeTypeHandle.GetGenericTypeDefinition(this);
}
{
if (!IsGenericParameter)
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
- Contract.EndContractBlock();
Type[] constraints = new RuntimeTypeHandle(this).GetConstraints();
{
if (rank <= 0)
throw new IndexOutOfRangeException();
- Contract.EndContractBlock();
return new RuntimeTypeHandle(this).MakeArray(rank);
}
{
if (IsGenericParameter)
throw new InvalidOperationException(SR.Arg_GenericParameter);
- Contract.EndContractBlock();
#region Preconditions
if ((bindingFlags & InvocationMask) == 0)
#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.
{
if ((object)attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
{
if ((object)attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (ContainsGenericParameters)
throw new ArgumentException(
SR.Format(SR.Acc_CreateGenericEx, this));
- Contract.EndContractBlock();
Type elementType = this.GetRootElementType();
using System.Runtime.Serialization;
using System.Threading;
using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
public static class RuntimeHelpers
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
/// <param name="task">The <see cref="System.Threading.Tasks.Task"/> to be awaited.</param>
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;
}
/// <summary>Throws an exception to handle a task that completed in a state other than RanToCompletion.</summary>
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)
/// <returns>The action to use as the actual continuation.</returns>
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)
{
/// <param name="task">The <see cref="System.Threading.Tasks.Task{TResult}"/> to be awaited.</param>
internal TaskAwaiter(Task<TResult> 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;
}
/// </param>
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);
}
/// </param>
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;
}
/// </param>
internal ConfiguredTaskAwaiter(Task<TResult> 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;
}
// See the LICENSE file in the project root for more information.
using System;
-using System.Diagnostics.Contracts;
namespace System.Runtime.CompilerServices
{
public TypeDependencyAttribute(string typeName)
{
if (typeName == null) throw new ArgumentNullException(nameof(typeName));
- Contract.EndContractBlock();
this.typeName = typeName;
}
}
using System;
using System.Security;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Diagnostics.Tracing;
using System.Threading;
using System.Threading.Tasks;
{
// Validate arguments
if (continuation == null) throw new ArgumentNullException(nameof(continuation));
- Contract.EndContractBlock();
if (TplEtwProvider.Log.IsEnabled())
{
using System.Runtime;
using System.Runtime.Versioning;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
-using System.Diagnostics.Contracts;
namespace System.Runtime
{
{
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.");
{
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Enum);
}
- Contract.EndContractBlock();
GC.SetLOHCompactionMode((int)value);
}
using System;
using System.Reflection;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Runtime.InteropServices
{
using System;
using System.Runtime.CompilerServices;
using System.Threading;
- using System.Diagnostics.Contracts;
#if BIT64
using nint = System.Int64;
#else
// 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);
public static GCHandle FromIntPtr(IntPtr value)
{
ValidateHandle(value);
- Contract.EndContractBlock();
#if MDA_SUPPORTED
IntPtr handle = value;
using Win32Native = Microsoft.Win32.Win32Native;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
using System.Runtime.InteropServices.ComTypes;
using System.StubHelpers;
if (structure == null)
throw new ArgumentNullException(nameof(structure));
// we never had a check for generics here
- Contract.EndContractBlock();
return SizeOfHelper(structure.GetType(), true);
}
return SizeOf((object)structure);
}
- [Pure]
public static int SizeOf(Type t)
{
if (t == null)
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);
}
{
if (t == null)
throw new ArgumentNullException(nameof(t));
- Contract.EndContractBlock();
FieldInfo f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (f == null)
{
if (m == null)
throw new ArgumentNullException(nameof(m));
- Contract.EndContractBlock();
RuntimeMethodInfo rmi = m as RuntimeMethodInfo;
{
if (c == null)
throw new ArgumentNullException(nameof(c));
- Contract.EndContractBlock();
MethodInfo[] mi = c.GetMethods();
if (mi != null)
{
if (m == null)
throw new ArgumentNullException(nameof(m));
- Contract.EndContractBlock();
RuntimeModule rtModule = m as RuntimeModule;
if (rtModule == null)
{
if (typeInfo == null)
throw new ArgumentNullException(nameof(typeInfo));
- Contract.EndContractBlock();
String strTypeLibName = null;
String strDocString = null;
{
if (o == null)
throw new ArgumentNullException(nameof(o));
- Contract.EndContractBlock();
__ComObject co = null;
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));
throw new ArgumentException(SR.Argument_TypeMustNotBeComImport, nameof(type));
if (type.IsGenericType)
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type));
- Contract.EndContractBlock();
IList<CustomAttributeData> cas = CustomAttributeData.GetCustomAttributes(type);
for (int i = 0; i < cas.Count; i++)
if (t == null)
throw new ArgumentNullException(nameof(t));
- Contract.EndContractBlock();
if ((t as RuntimeType) == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t));
{
if (d == null)
throw new ArgumentNullException(nameof(d));
- Contract.EndContractBlock();
return GetFunctionPointerForDelegateInternal(d);
}
{
throw new ArgumentNullException(nameof(s));
}
- Contract.EndContractBlock();
return s.MarshalToBSTR();
}
{
throw new ArgumentNullException(nameof(s));
}
- Contract.EndContractBlock();
return s.MarshalToString(globalAlloc: false, unicode: false);
}
{
throw new ArgumentNullException(nameof(s));
}
- Contract.EndContractBlock();
return s.MarshalToString(globalAlloc: false, unicode: true);
}
{
throw new ArgumentNullException(nameof(s));
}
- Contract.EndContractBlock();
return s.MarshalToString(globalAlloc: true, unicode: false);
}
{
throw new ArgumentNullException(nameof(s));
}
- Contract.EndContractBlock();
return s.MarshalToString(globalAlloc: true, unicode: true); ;
}
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Runtime.InteropServices
{
{
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);
{
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);
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();
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();
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
}
// int Count { get }
- [Pure]
internal int Count()
{
IBindableVector _this = Unsafe.As<IBindableVector>(this);
}
// 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)
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
}
// bool IsFixedSize { get }
- [Pure]
internal bool IsFixedSize()
{
return false;
}
// bool IsReadOnly { get }
- [Pure]
internal bool IsReadOnly()
{
return false;
using System;
using System.Collections.Generic;
-using System.Diagnostics.Contracts;
+using System.Diagnostics;
namespace System.Runtime.InteropServices.WindowsRuntime
{
}
// IKeyValuePair<K, V> implementation
- [Pure]
public K Key
{
get { return _pair.Key; }
}
- [Pure]
public V Value
{
get { return _pair.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<K, V> unboxedPair = (KeyValuePair<K, V>)pair;
return new CLRIKeyValuePairImpl<K, V>(ref unboxedPair);
// 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<K, V> reference = (CLRIKeyValuePairImpl<K, V>)wrapper;
return reference._pair;
//
using System;
-using System.Diagnostics.Contracts;
+using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Security;
public PropertyType Type
{
- [Pure]
get { return _type; }
}
public bool IsNumericScalar
{
- [Pure]
get
{
return IsNumericScalarImpl(_type, _data);
}
}
- [Pure]
public Byte GetUInt8()
{
return CoerceScalarValue<Byte>(PropertyType.UInt8);
}
- [Pure]
public Int16 GetInt16()
{
return CoerceScalarValue<Int16>(PropertyType.Int16);
return CoerceScalarValue<UInt16>(PropertyType.UInt16);
}
- [Pure]
public Int32 GetInt32()
{
return CoerceScalarValue<Int32>(PropertyType.Int32);
}
- [Pure]
public UInt32 GetUInt32()
{
return CoerceScalarValue<UInt32>(PropertyType.UInt32);
}
- [Pure]
public Int64 GetInt64()
{
return CoerceScalarValue<Int64>(PropertyType.Int64);
}
- [Pure]
public UInt64 GetUInt64()
{
return CoerceScalarValue<UInt64>(PropertyType.UInt64);
}
- [Pure]
public Single GetSingle()
{
return CoerceScalarValue<Single>(PropertyType.Single);
}
- [Pure]
public Double GetDouble()
{
return CoerceScalarValue<Double>(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<String>(PropertyType.String);
}
- [Pure]
public Guid GetGuid()
{
return CoerceScalarValue<Guid>(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<Point>(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<Size>(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<Rect>(IReferenceFactory.s_rectType);
}
- [Pure]
public Byte[] GetUInt8Array()
{
return CoerceArrayValue<Byte>(PropertyType.UInt8Array);
}
- [Pure]
public Int16[] GetInt16Array()
{
return CoerceArrayValue<Int16>(PropertyType.Int16Array);
}
- [Pure]
public UInt16[] GetUInt16Array()
{
return CoerceArrayValue<UInt16>(PropertyType.UInt16Array);
}
- [Pure]
public Int32[] GetInt32Array()
{
return CoerceArrayValue<Int32>(PropertyType.Int32Array);
}
- [Pure]
public UInt32[] GetUInt32Array()
{
return CoerceArrayValue<UInt32>(PropertyType.UInt32Array);
}
- [Pure]
public Int64[] GetInt64Array()
{
return CoerceArrayValue<Int64>(PropertyType.Int64Array);
}
- [Pure]
public UInt64[] GetUInt64Array()
{
return CoerceArrayValue<UInt64>(PropertyType.UInt64Array);
}
- [Pure]
public Single[] GetSingleArray()
{
return CoerceArrayValue<Single>(PropertyType.SingleArray);
}
- [Pure]
public Double[] GetDoubleArray()
{
return CoerceArrayValue<Double>(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<String>(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<Guid>(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<Point>(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<Size>(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<Rect>(IReferenceFactory.s_rectType);
}
}
// Unbox the data stored in the property value to a structurally equivilent type
- [Pure]
private unsafe T Unbox<T>(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)
{
}
// Convert the array stored in the property value to a structurally equivilent array type
- [Pure]
private unsafe T[] UnboxArray<T>(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)
using System;
using System.Collections;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Reflection;
using System.Security;
[System.Runtime.CompilerServices.FriendAccessAllowed]
internal static Object UnboxHelper(Object wrapper)
{
- Contract.Requires(wrapper != null);
+ Debug.Assert(wrapper != null);
IReference<T> reference = (IReference<T>)wrapper;
Debug.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<" + typeof(T) + ">, but that failed.");
return reference.Value;
[System.Runtime.CompilerServices.FriendAccessAllowed]
internal static Object UnboxHelper(Object wrapper)
{
- Contract.Requires(wrapper != null);
+ Debug.Assert(wrapper != null);
IReferenceArray<T> reference = (IReferenceArray<T>)wrapper;
Debug.Assert(reference != null, "CLRIReferenceArrayImpl::UnboxHelper - QI'ed for IReferenceArray<" + typeof(T) + ">, but that failed.");
T[] marshaled = reference.Value;
internal static Object CreateIReference(Object obj)
{
- Contract.Requires(obj != null, "Null should not be boxed.");
- Contract.Ensures(Contract.Result<Object>() != null);
+ Debug.Assert(obj != null, "Null should not be boxed.");
Type type = obj.GetType();
internal static Object CreateIReferenceArray(Array obj)
{
- Contract.Requires(obj != null);
- Contract.Requires(obj.GetType().IsArray);
- Contract.Ensures(Contract.Result<Object>() != null);
+ Debug.Assert(obj != null);
+ Debug.Assert(obj.GetType().IsArray);
Type type = obj.GetType().GetElementType();
{
if (data == null)
throw new ArgumentNullException(nameof(data));
- Contract.EndContractBlock();
firstItemIndex = 0;
lastItemIndex = data.Count - 1;
internal IKeyValuePairEnumerator(KeyValuePair<TKey, TValue>[] 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;
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;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
internal EnumeratorToIteratorAdapter(IEnumerator<T> enumerator)
{
- Contract.Requires(enumerator != null);
+ Debug.Assert(enumerator != null);
m_enumerator = enumerator;
}
using System;
using System.Collections.Generic;
-using System.Diagnostics.Contracts;
+using System.Diagnostics;
using System.Threading;
namespace System.Runtime.InteropServices.WindowsRuntime
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.
// 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
using System.Security;
using System.Collections;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
namespace System.Runtime.InteropServices.WindowsRuntime
//
using System;
-using System.Diagnostics.Contracts;
namespace System.Runtime.InteropServices.WindowsRuntime
{
{
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;
}
}
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;
//
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)
//
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);
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)
//
// IBindableVector implementation (forwards to IBindableVector / IVector<T>)
//
- [Pure]
object IBindableVector.GetAt(uint index)
{
IBindableVector bindableVector = GetIBindableVectorNoThrow();
}
}
- [Pure]
uint IBindableVector.Size
{
get
}
}
- [Pure]
IBindableVectorView IBindableVector.GetView()
{
IBindableVector bindableVector = GetIBindableVectorNoThrow();
_vectorView = vectorView;
}
- [Pure]
object IBindableVectorView.GetAt(uint index)
{
return _vectorView.GetAt(index);
}
- [Pure]
uint IBindableVectorView.Size
{
get
}
}
- [Pure]
bool IBindableVectorView.IndexOf(object value, out uint index)
{
return _vectorView.IndexOf(ConvertTo<T>(value), out index);
}
}
- [Pure]
bool IBindableVector.IndexOf(object value, out uint index)
{
IBindableVector bindableVector = GetIBindableVectorNoThrow();
//
// IBindableVectorView implementation (forwarding to IBindableVectorView or IVectorView<T>)
//
- [Pure]
object IBindableVectorView.GetAt(uint index)
{
IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow();
return GetVectorViewOfT().GetAt(index);
}
- [Pure]
uint IBindableVectorView.Size
{
get
}
}
- [Pure]
bool IBindableVectorView.IndexOf(object value, out uint index)
{
IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow();
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.
[WindowsRuntimeImport]
internal interface IIterable<T> : IEnumerable<T>
{
- [Pure]
IIterator<T> First();
}
[WindowsRuntimeImport]
internal interface IBindableIterable
{
- [Pure]
IBindableIterator First();
}
}
//
using System;
-using System.Diagnostics.Contracts;
namespace System.Runtime.InteropServices.WindowsRuntime
{
[Guid("6a79e863-4300-459a-9966-cbb660963ee1")]
internal interface IIterator<T>
{
- [Pure]
T Current
{
get;
}
- [Pure]
bool HasCurrent
{
get;
bool MoveNext();
- [Pure]
int GetMany([Out] T[] items);
}
[Guid("6a1d6c07-076d-49f2-8314-f52c9c9a8331")]
internal interface IBindableIterator
{
- [Pure]
object Current
{
get;
}
- [Pure]
bool HasCurrent
{
get;
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
[WindowsRuntimeImport]
internal interface IMap<K, V> : IIterable<IKeyValuePair<K, V>>
{
- [Pure]
V Lookup(K key);
- [Pure]
uint Size { get; }
- [Pure]
bool HasKey(K key);
- [Pure]
IReadOnlyDictionary<K, V> GetView(); // Really an IMapView<K, V>
bool Insert(K key, V value);
void Remove(K key);
[WindowsRuntimeImport]
internal interface IMapView<K, V> : IIterable<IKeyValuePair<K, V>>
{
- [Pure]
V Lookup(K key);
- [Pure]
uint Size { get; }
- [Pure]
bool HasKey(K key);
- [Pure]
void Split(out IMapView<K, V> first, out IMapView<K, V> second);
}
[WindowsRuntimeImport]
internal interface IKeyValuePair<K, V>
{
- [Pure]
K Key { get; }
- [Pure]
V Value { get; }
}
}
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
if (key == null)
throw new ArgumentNullException(nameof(key));
- Contract.EndContractBlock();
IMapView<K, V> _this = Unsafe.As<IMapView<K, V>>(this);
return Lookup(_this, key);
}
// bool ContainsKey(K key)
- [Pure]
internal bool ContainsKey<K, V>(K key)
{
if (key == null)
private static V Lookup<K, V>(IMapView<K, V> _this, K key)
{
- Contract.Requires(null != key);
+ Debug.Assert(null != key);
try
{
//
using System;
-using System.Diagnostics.Contracts;
namespace System.Runtime.InteropServices.WindowsRuntime
{
{
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();
}
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
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
[WindowsRuntimeImport]
internal interface IVector<T> : IIterable<T>
{
- [Pure]
T GetAt(uint index);
- [Pure]
uint Size { get; }
- [Pure]
IReadOnlyList<T> GetView(); // Really an IVectorView<T>.
- [Pure]
bool IndexOf(T value, out uint index);
void SetAt(uint index, T value);
void InsertAt(uint index, T value);
void Append(T value);
void RemoveAtEnd();
void Clear();
- [Pure]
uint GetMany(uint startIndex, [Out] T[] items);
void ReplaceAll(T[] items);
}
[WindowsRuntimeImport]
internal interface IVector_Raw<T> : IIterable<T>
{
- [Pure]
T GetAt(uint index);
- [Pure]
uint Size { get; }
- [Pure]
IVectorView<T> GetView();
- [Pure]
bool IndexOf(T value, out uint index);
void SetAt(uint index, T value);
void InsertAt(uint index, T value);
[WindowsRuntimeImport]
internal interface IVectorView<T> : IIterable<T>
{
- [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);
}
[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);
[WindowsRuntimeImport]
internal interface IBindableVectorView : IBindableIterable
{
- [Pure]
object GetAt(uint index);
- [Pure]
uint Size { get; }
- [Pure]
bool IndexOf(object value, out uint index);
}
}
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
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;
internal IteratorToEnumeratorAdapter(IIterator<T> iterator)
{
- Contract.Requires(iterator != null);
+ Debug.Assert(iterator != null);
m_iterator = iterator;
m_hadCurrent = true;
m_isInitialized = false;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
if (list == null)
throw new ArgumentNullException(nameof(list));
- Contract.EndContractBlock();
this.list = list;
}
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
//
using System;
-using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
}
// int Count { get }
- [Pure]
internal int Count<K, V>()
{
object _this = Unsafe.As<object>(this);
if (array.Length - arrayIndex < Count<K, V>())
throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection);
- Contract.EndContractBlock();
IIterable<KeyValuePair<K, V>> _this = Unsafe.As<IIterable<KeyValuePair<K, V>>>(this);
foreach (KeyValuePair<K, V> mapping in _this)
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
if (key == null)
throw new ArgumentNullException(nameof(key));
- Contract.EndContractBlock();
IMap<K, V> _this = Unsafe.As<IMap<K, V>>(this);
return Lookup(_this, key);
if (key == null)
throw new ArgumentNullException(nameof(key));
- Contract.EndContractBlock();
IMap<K, V> _this = Unsafe.As<IMap<K, V>>(this);
Insert(_this, key, value);
}
// bool ContainsKey(K key)
- [Pure]
internal bool ContainsKey<K, V>(K key)
{
if (key == null)
if (ContainsKey<K, V>(key))
throw new ArgumentException(SR.Argument_AddingDuplicate);
- Contract.EndContractBlock();
IMap<K, V> _this = Unsafe.As<IMap<K, V>>(this);
Insert(_this, key, value);
private static V Lookup<K, V>(IMap<K, V> _this, K key)
{
- Contract.Requires(null != key);
+ Debug.Assert(null != key);
try
{
private static bool Insert<K, V>(IMap<K, V> _this, K key, V value)
{
- Contract.Requires(null != key);
+ Debug.Assert(null != key);
bool replaced = _this.Insert(key, value);
return replaced;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
}
// int Count { get }
- [Pure]
internal int Count<K, V>()
{
object _this = Unsafe.As<object>(this);
//
using System;
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
}
// int Count { get }
- [Pure]
internal int Count<T>()
{
IVector<T> _this = Unsafe.As<IVector<T>>(this);
if (array.Length - arrayIndex < Count<T>())
throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection);
- Contract.EndContractBlock();
IVector<T> _this = Unsafe.As<IVector<T>>(this);
int count = Count<T>();
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
}
// int Count { get }
- [Pure]
internal int Count<T>()
{
IVectorView<T> _this = Unsafe.As<IVectorView<T>>(this);
using System;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
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.
{
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.
{
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 -
Action<EventRegistrationToken> 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;
// Get the event registration token table for an event. These are indexed by the remove method of the event.
private static Dictionary<object, EventRegistrationTokenList> GetEventRegistrationTokenTable(object instance, Action<EventRegistrationToken> 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)
{
internal static void RemoveEventHandler<T>(Action<EventRegistrationToken> removeMethod, T handler)
{
- Contract.Requires(removeMethod != null);
+ Debug.Assert(removeMethod != null);
object instance = removeMethod.Target;
Dictionary<object, EventRegistrationTokenList> registrationTokens = GetEventRegistrationTokenTable(instance, removeMethod);
internal static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod)
{
- Contract.Requires(removeMethod != null);
+ Debug.Assert(removeMethod != null);
object instance = removeMethod.Target;
Dictionary<object, EventRegistrationTokenList> registrationTokens = GetEventRegistrationTokenTable(instance, removeMethod);
{
// 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);
private static ConditionalWeakTable<object, EventRegistrationTokenListWithCount> GetEventRegistrationTokenTableNoCreate(object instance, Action<EventRegistrationToken> 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<object, EventRegistrationTokenListWithCount> GetOrCreateEventRegistrationTokenTable(object instance, Action<EventRegistrationToken> 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);
}
// Get the event registration token table for an event. These are indexed by the remove method of the event.
private static ConditionalWeakTable<object, EventRegistrationTokenListWithCount> GetEventRegistrationTokenTableInternal(object instance, Action<EventRegistrationToken> 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;
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)
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;
using System;
using System.Reflection;
-using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.Versioning;
using System.Runtime.CompilerServices;
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
{
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;
using System;
using System.Globalization;
-using System.Diagnostics.Contracts;
namespace System.Runtime.Serialization
{
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
return System.Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
}
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
return System.Convert.ChangeType(value, typeCode, CultureInfo.InvariantCulture);
}
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
return System.Convert.ToBoolean(value, CultureInfo.InvariantCulture);
}
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
return System.Convert.ToChar(value, CultureInfo.InvariantCulture);
}
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
return System.Convert.ToSByte(value, CultureInfo.InvariantCulture);
}
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
return System.Convert.ToByte(value, CultureInfo.InvariantCulture);
}
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
return System.Convert.ToInt16(value, CultureInfo.InvariantCulture);
}
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
return System.Convert.ToUInt16(value, CultureInfo.InvariantCulture);
}
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
return System.Convert.ToInt32(value, CultureInfo.InvariantCulture);
}
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
return System.Convert.ToUInt32(value, CultureInfo.InvariantCulture);
}
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
return System.Convert.ToInt64(value, CultureInfo.InvariantCulture);
}
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
return System.Convert.ToUInt64(value, CultureInfo.InvariantCulture);
}
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
return System.Convert.ToSingle(value, CultureInfo.InvariantCulture);
}
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
return System.Convert.ToDouble(value, CultureInfo.InvariantCulture);
}
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
return System.Convert.ToDecimal(value, CultureInfo.InvariantCulture);
}
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
return System.Convert.ToDateTime(value, CultureInfo.InvariantCulture);
}
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
return System.Convert.ToString(value, CultureInfo.InvariantCulture);
}
}
using System.Text;
using System.Globalization;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Runtime.Serialization
{
{
throw new ArgumentNullException(nameof(type));
}
- Contract.EndContractBlock();
if (!(type is RuntimeType))
{
using System.Reflection;
using System.Globalization;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Security;
using System.Runtime.CompilerServices;
throw new ArgumentNullException(nameof(converter));
}
- Contract.EndContractBlock();
objectType = type;
m_fullTypeName = type.FullName;
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
m_fullTypeName = value;
isFullTypeNameSetExplicit = true;
{
throw new ArgumentNullException(nameof(value));
}
- Contract.EndContractBlock();
if (requireSameTokenInPartialTrust)
{
DemandForUnsafeAssemblyNameAssignments(m_assemName, value);
{
throw new ArgumentNullException(nameof(type));
}
- Contract.EndContractBlock();
if (requireSameTokenInPartialTrust)
{
{
throw new ArgumentNullException(nameof(type));
}
- Contract.EndContractBlock();
AddValueInternal(name, value, type);
}
{
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))
{
throw new ArgumentNullException(nameof(type));
}
- Contract.EndContractBlock();
RuntimeType rt = type as RuntimeType;
if (rt == null)
using System.Globalization;
using System.Security;
using Microsoft.Win32.SafeHandles;
- using System.Diagnostics.Contracts;
using StackCrawlMark = System.Threading.StackCrawlMark;
public unsafe struct RuntimeTypeHandle : ISerializable
{
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));
return handle.Value == Value;
}
- [Pure]
internal bool IsNullHandle()
{
return m_value == null;
return _GetCurrentMethod(ref stackMark);
}
- [Pure]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern MethodAttributes GetAttributes(RuntimeMethodHandleInternal method);
internal static int GetSlot(IRuntimeMethodInfo method)
{
- Contract.Requires(method != null);
+ Debug.Assert(method != null);
int slot = RuntimeMethodHandle.GetSlot(method.Value);
GC.KeepAlive(method);
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System
{
using System.Collections;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
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)
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;
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)
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;
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
// 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);
// 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;
// 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]
{
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
- Contract.EndContractBlock();
if (object.ReferenceEquals(strA, strB))
{
// 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);
}
// 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;
// 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
// 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
// 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;
// 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;
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)
{
// Compares strA and strB using an ordinal (code-point) comparison.
//
- [Pure]
public static int CompareOrdinal(String strA, String strB)
{
if (object.ReferenceEquals(strA, 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)
// 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)
// Determines the sorting relation of StrB to the current instance.
//
- [Pure]
public int CompareTo(String strB)
{
return string.Compare(this, strB, StringComparison.CurrentCulture);
// 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)
{
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
- Contract.EndContractBlock();
if ((Object)this == (Object)value)
{
}
}
- [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)
{
return referenceCulture.CompareInfo.IsSuffix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
- [Pure]
public bool EndsWith(char value)
{
int thisLen = Length;
}
// Determines whether two strings match.
- [Pure]
public bool Equals(String value)
{
if (object.ReferenceEquals(this, 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)
{
// Determines whether two Strings match.
- [Pure]
public static bool Equals(String a, String b)
{
if ((Object)a == (Object)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)
{
// 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)
{
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
- Contract.EndContractBlock();
if ((Object)this == (Object)value)
{
}
}
- [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)
{
return referenceCulture.CompareInfo.IsPrefix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
- [Pure]
public bool StartsWith(char value) => Length != 0 && _firstChar == value;
}
}
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
{
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)
public static String Concat(Object arg0)
{
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
-
if (arg0 == null)
{
return String.Empty;
public static String Concat(Object arg0, Object arg1)
{
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
-
if (arg0 == null)
{
arg0 = String.Empty;
public static String Concat(Object arg0, Object arg1, Object arg2)
{
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
-
if (arg0 == null)
{
arg0 = String.Empty;
{
throw new ArgumentNullException(nameof(args));
}
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
if (args.Length <= 1)
{
{
if (values == null)
throw new ArgumentNullException(nameof(values));
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
using (IEnumerator<T> en = values.GetEnumerator())
{
{
if (values == null)
throw new ArgumentNullException(nameof(values));
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
using (IEnumerator<string> en = values.GetEnumerator())
{
public static String Concat(String str0, String str1)
{
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.Ensures(Contract.Result<String>().Length ==
- (str0 == null ? 0 : str0.Length) +
- (str1 == null ? 0 : str1.Length));
- Contract.EndContractBlock();
-
if (IsNullOrEmpty(str0))
{
if (IsNullOrEmpty(str1))
public static String Concat(String str0, String str1, String str2)
{
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.Ensures(Contract.Result<String>().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);
public static String Concat(String str0, String str1, String str2, String str3)
{
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.Ensures(Contract.Result<String>().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);
{
if (values == null)
throw new ArgumentNullException(nameof(values));
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
if (values.Length <= 1)
{
public static String Format(String format, Object arg0)
{
- Contract.Ensures(Contract.Result<String>() != null);
return FormatHelper(null, format, new ParamsArray(arg0));
}
public static String Format(String format, Object arg0, Object arg1)
{
- Contract.Ensures(Contract.Result<String>() != 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<String>() != null);
return FormatHelper(null, format, new ParamsArray(arg0, arg1, arg2));
}
// 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<String>() != null);
- Contract.EndContractBlock();
return FormatHelper(null, format, new ParamsArray(args));
}
public static String Format(IFormatProvider provider, String format, Object arg0)
{
- Contract.Ensures(Contract.Result<String>() != null);
return FormatHelper(provider, format, new ParamsArray(arg0));
}
public static String Format(IFormatProvider provider, String format, Object arg0, Object arg1)
{
- Contract.Ensures(Contract.Result<String>() != 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<String>() != null);
return FormatHelper(provider, format, new ParamsArray(arg0, arg1, arg2));
}
// 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<String>() != null);
- Contract.EndContractBlock();
return FormatHelper(provider, format, new ParamsArray(args));
}
throw new ArgumentNullException(nameof(value));
if (startIndex < 0 || startIndex > this.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex));
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.Ensures(Contract.Result<String>().Length == this.Length + value.Length);
- Contract.EndContractBlock();
int oldLength = Length;
int insertLength = value.Length;
//
//
- [Pure]
public String PadLeft(int totalWidth)
{
return PadLeft(totalWidth, ' ');
}
- [Pure]
public String PadLeft(int totalWidth, char paddingChar)
{
if (totalWidth < 0)
return result;
}
- [Pure]
public String PadRight(int totalWidth)
{
return PadRight(totalWidth, ' ');
}
- [Pure]
public String PadRight(int totalWidth, char paddingChar)
{
if (totalWidth < 0)
if (count > Length - startIndex)
throw new ArgumentOutOfRangeException(nameof(count),
SR.ArgumentOutOfRange_IndexCount);
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.Ensures(Contract.Result<String>().Length == this.Length - count);
- Contract.EndContractBlock();
if (count == 0)
return this;
SR.ArgumentOutOfRange_StartIndexLessThanLength);
}
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
return Substring(0, startIndex);
}
public string Replace(string oldValue, string newValue, bool ignoreCase, CultureInfo culture)
{
- Contract.Ensures(Contract.Result<String>() != 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<String>() != null);
- Contract.EndContractBlock();
-
switch (comparisonType)
{
case StringComparison.CurrentCulture:
//
public String Replace(char oldChar, char newChar)
{
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.Ensures(Contract.Result<String>().Length == this.Length);
- Contract.EndContractBlock();
-
if (oldChar == newChar)
return this;
if (oldValue == null)
throw new ArgumentNullException(nameof(oldValue));
// Note that if newValue is null, we treat it like String.Empty.
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
return ReplaceInternal(oldValue, newValue);
}
public unsafe String[] Split(char separator, StringSplitOptions options = StringSplitOptions.None)
{
- Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(&separator, 1, int.MaxValue, options);
}
public unsafe String[] Split(char separator, int count, StringSplitOptions options = StringSplitOptions.None)
{
- Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(&separator, 1, count, options);
}
//
public String[] Split(params char[] separator)
{
- Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(separator, Int32.MaxValue, StringSplitOptions.None);
}
//
public string[] Split(char[] separator, int count)
{
- Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(separator, count, StringSplitOptions.None);
}
public String[] Split(char[] separator, StringSplitOptions options)
{
- Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(separator, Int32.MaxValue, options);
}
public String[] Split(char[] separator, int count, StringSplitOptions options)
{
- Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(separator, count, options);
}
if (options < StringSplitOptions.None || options > StringSplitOptions.RemoveEmptyEntries)
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, options));
- Contract.Ensures(Contract.Result<String[]>() != null);
- Contract.EndContractBlock();
bool omitEmptyEntries = (options == StringSplitOptions.RemoveEmptyEntries);
public String[] Split(String separator, StringSplitOptions options = StringSplitOptions.None)
{
- Contract.Ensures(Contract.Result<String[]>() != 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<String[]>() != null);
return SplitInternal(separator ?? String.Empty, null, count, options);
}
public String[] Split(String[] separator, StringSplitOptions options)
{
- Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(null, separator, Int32.MaxValue, options);
}
public String[] Split(String[] separator, Int32 count, StringSplitOptions options)
{
- Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(null, separator, count, options);
}
{
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)options));
}
- Contract.EndContractBlock();
bool omitEmptyEntries = (options == StringSplitOptions.RemoveEmptyEntries);
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<String[]>() != null);
+ Debug.Assert(numReplaces >= 0);
+ Debug.Assert(count >= 2);
int currIndex = 0;
int arrIndex = 0;
// 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<String[]>() != 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
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexLength);
}
- Contract.EndContractBlock();
if (length == 0)
{
}
// Creates a copy of this string in lower case.
- [Pure]
public String ToLower()
{
- Contract.Ensures(Contract.Result<String>() != 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<String>() != 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<String>() != 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<String>() != 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<String>() != 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<String>() != 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<string>() != null);
- Contract.EndContractBlock();
-
return TrimWhiteSpaceHelper(TrimType.Both);
}
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)
// 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;
{
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);
// 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)
// 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)
// 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);
// 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);
// 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)
{
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
if (count < 0 || startIndex > this.Length - count)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
- Contract.EndContractBlock();
switch (comparisonType)
{
// 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)
//
//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);
// 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))
using System.Runtime.Versioning;
using Microsoft.Win32;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
using System.Security;
//
//
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,
// 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]
{
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)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index);
- Contract.EndContractBlock();
if (length > 0)
{
return Array.Empty<char>();
}
- [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;
/// 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)]
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);
if (startIndex > value.Length - length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
- Contract.EndContractBlock();
if (length > 0)
{
{
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;
// Returns this string.
public override String ToString()
{
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
return this;
}
public String ToString(IFormatProvider provider)
{
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
return this;
}
// There's no point in cloning a string since they're immutable, so we simply return this.
public Object Clone()
{
- Contract.Ensures(Contract.Result<Object>() != null);
- Contract.EndContractBlock();
return this;
}
{
throw new ArgumentNullException(nameof(str));
}
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
int length = str.Length;
{
throw new ArgumentNullException(nameof(str));
}
- Contract.Ensures(Contract.Result<String>().Length == str.Length);
- Contract.Ensures(str.Equals(Contract.Result<String>()));
- 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<String>() == null || Contract.Result<String>().Length == str.Length);
- Contract.EndContractBlock();
return Thread.GetDomain().IsStringInterned(str);
}
public CharEnumerator GetEnumerator()
{
- Contract.Ensures(Contract.Result<CharEnumerator>() != 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<char> IEnumerable<char>.GetEnumerator()
{
- Contract.Ensures(Contract.Result<IEnumerator<char>>() != 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<IEnumerator>() != 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);
}
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
internal static class AnsiCharMarshaler
{
static internal unsafe Exception ConvertToManaged(int hr)
{
- Contract.Ensures(Contract.Result<Exception>() != null || hr >= 0);
-
if (!Environment.IsWinRTSupported)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Text
{
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.AccessControl;
- using System.Diagnostics.Contracts;
[ComVisibleAttribute(true)]
public class EventWaitHandle : WaitHandle
}
#endif
}
- Contract.EndContractBlock();
uint eventFlags = initialState ? Win32Native.CREATE_EVENT_INITIAL_SET : 0;
switch (mode)
}
#endif
}
- Contract.EndContractBlock();
Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
uint eventFlags = initialState ? Win32Native.CREATE_EVENT_INITIAL_SET : 0;
throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name));
}
- Contract.EndContractBlock();
result = null;
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Threading
{
/// </summary>
private void EnsureLockObjectCreated()
{
- Contract.Ensures(m_lock != null);
-
if (m_lock != null)
return;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Threading
{
{
throw new ArgumentNullException(nameof(obj));
}
- Contract.EndContractBlock();
ObjPulse(obj);
}
{
throw new ArgumentNullException(nameof(obj));
}
- Contract.EndContractBlock();
ObjPulseAll(obj);
}
using System.Runtime.Versioning;
using System.Security;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
public sealed class Mutex : WaitHandle
{
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);
throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name));
}
#endif
- Contract.EndContractBlock();
result = null;
using System.Security;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Collections.Concurrent;
namespace System.Threading
{
if (nativeOverlappedPtr == null)
throw new ArgumentNullException(nameof(nativeOverlappedPtr));
- Contract.EndContractBlock();
Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped;
{
if (nativeOverlappedPtr == null)
throw new ArgumentNullException(nameof(nativeOverlappedPtr));
- Contract.EndContractBlock();
Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped;
OverlappedData.FreeNativeOverlapped(nativeOverlappedPtr);
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
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
/// <returns>true if the waiter was in the list; otherwise, false.</returns>
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.
using System.Reflection;
using System.Security;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
{
throw new ArgumentNullException(nameof(waitHandles));
}
- Contract.EndContractBlock();
return WaitHelperNative(waitHandles, waitAll, millisecondsTimeout);
}
using System;
using System.Security;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Security;
namespace System.Threading.Tasks
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;
/// <summary>Completes the completion task asynchronously.</summary>
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
/// <param name="faultedTask">The faulted worker task that's initiating the shutdown.</param>
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);
/// </summary>
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
{
/// </summary>
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
{
/// <param name="processingMode">The processing mode of this scheduler.</param>
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.");
/// <param name="scheduler">The scheduler being debugged.</param>
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;
}
/// <param name="pair">The pair being debugged.</param>
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;
}
[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,
using System.Runtime.CompilerServices;
using System.Threading;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.Versioning;
namespace System.Threading.Tasks
Task<TResult> 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;
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);
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");
TaskFactory.CheckFromAsyncOptions(creationOptions, true);
if (endFunction == null && endAction == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endFunction);
- 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");
TaskFactory.CheckFromAsyncOptions(creationOptions, true);
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");
TaskFactory.CheckFromAsyncOptions(creationOptions, true);
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");
TaskFactory.CheckFromAsyncOptions(creationOptions, true);
/// <param name="endMethod">The end method.</param>
internal FromAsyncTrimPromise(TInstance thisRef, Func<TInstance, IAsyncResult, TResult> 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;
}
{
// Validate argument
if (asyncResult == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.asyncResult);
- Contract.EndContractBlock();
var promise = asyncResult.AsyncState as FromAsyncTrimPromise<TInstance>;
if (promise == null) ThrowHelper.ThrowArgumentException(ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple, ExceptionArgument.asyncResult);
public Task<TResult> ContinueWhenAll(Task[] tasks, Func<Task[], TResult> continuationFunction)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
- Contract.EndContractBlock();
return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
public Task<TResult> ContinueWhenAll(Task[] tasks, Func<Task[], TResult> continuationFunction, CancellationToken cancellationToken)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
- Contract.EndContractBlock();
return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
public Task<TResult> ContinueWhenAll(Task[] tasks, Func<Task[], TResult> continuationFunction, TaskContinuationOptions continuationOptions)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
- Contract.EndContractBlock();
return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
- Contract.EndContractBlock();
return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
}
public Task<TResult> ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
- Contract.EndContractBlock();
return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
CancellationToken cancellationToken)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
- Contract.EndContractBlock();
return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
TaskContinuationOptions continuationOptions)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
- Contract.EndContractBlock();
return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
- Contract.EndContractBlock();
return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
}
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<TAntecedentResult>[] tasksCopy = TaskFactory.CheckMultiContinuationTasksAndCopy<TAntecedentResult>(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);
public Task<TResult> ContinueWhenAny(Task[] tasks, Func<Task, TResult> continuationFunction)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
- Contract.EndContractBlock();
return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
public Task<TResult> ContinueWhenAny(Task[] tasks, Func<Task, TResult> continuationFunction, CancellationToken cancellationToken)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
- Contract.EndContractBlock();
return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
public Task<TResult> ContinueWhenAny(Task[] tasks, Func<Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
- Contract.EndContractBlock();
return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
- Contract.EndContractBlock();
return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
}
public Task<TResult> ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
- Contract.EndContractBlock();
return ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
CancellationToken cancellationToken)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
- Contract.EndContractBlock();
return ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
TaskContinuationOptions continuationOptions)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
- Contract.EndContractBlock();
return ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
- Contract.EndContractBlock();
return ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
}
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<Task> starter = TaskFactory.CommonCWAnyLogic(tasks);
if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.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
var starter = TaskFactory.CommonCWAnyLogic(tasks);
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
namespace System.Threading.Tasks
/// <param name="segment">The segment in which to first attempt to store the item.</param>
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)
{
/// <returns>true if an item could be dequeued; otherwise, false.</returns>
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)
{
/// <param name="size">The size to use for this segment.</param>
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];
}
}
/// <param name="enumerable">The queue being debugged.</param>
public SingleProducerSingleConsumerQueue_DebugView(SingleProducerSingleConsumerQueue<T> queue)
{
- Contract.Requires(queue != null, "Expected a non-null queue.");
+ Debug.Assert(queue != null, "Expected a non-null queue.");
m_queue = queue;
}
}
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;
[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;
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action);
}
- Contract.EndContractBlock();
// Keep a link to the parent if attached
if (parent != null && (creationOptions & TaskCreationOptions.AttachedToParent) != 0)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
}
- Contract.EndContractBlock();
InternalRunSynchronously(scheduler, waitForCompletion: true);
}
//
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;
{
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
/// <param name="exceptionObject">An object representing either an Exception or a collection of Exceptions.</param>
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);
}
/// <param name="representsCancellation">Whether the exceptionObject is an OperationCanceledException representing cancellation.</param>
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;
/// </summary>
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)
/// </summary>
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");
/// <param name="unhandledException">The exception that went unhandled.</param>
private void HandleException(Exception unhandledException)
{
- Contract.Requires(unhandledException != null);
+ Debug.Assert(unhandledException != null);
OperationCanceledException exceptionAsOce = unhandledException as OperationCanceledException;
if (exceptionAsOce != null && IsCancellationRequested &&
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
{
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
/// <returns>true if the task was successfully canceled; otherwise, false.</returns>
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;
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
}
- Contract.EndContractBlock();
TaskCreationOptions creationOptions;
InternalTaskOptions internalOptions;
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
}
- Contract.EndContractBlock();
TaskCreationOptions creationOptions;
InternalTaskOptions internalOptions;
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
}
- Contract.EndContractBlock();
TaskCreationOptions creationOptions;
InternalTaskOptions internalOptions;
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
}
- Contract.EndContractBlock();
TaskCreationOptions creationOptions;
InternalTaskOptions internalOptions;
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);
// 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;
// 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.
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.millisecondsTimeout);
}
- Contract.EndContractBlock();
cancellationToken.ThrowIfCancellationRequested(); // early check before we make any allocations
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.millisecondsTimeout);
}
- Contract.EndContractBlock();
cancellationToken.ThrowIfCancellationRequested(); // early check before we make any allocations
public static Task<TResult> FromException<TResult>(Exception exception)
{
if (exception == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception);
- Contract.EndContractBlock();
var task = new Task<TResult>();
bool succeeded = task.TrySetException(exception);
{
if (!cancellationToken.IsCancellationRequested)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.cancellationToken);
- Contract.EndContractBlock();
return new Task(true, TaskCreationOptions.None, cancellationToken);
}
{
if (!cancellationToken.IsCancellationRequested)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.cancellationToken);
- Contract.EndContractBlock();
return new Task<TResult>(true, default(TResult), TaskCreationOptions.None, cancellationToken);
}
internal static Task<TResult> FromCancellation<TResult>(OperationCanceledException exception)
{
if (exception == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception);
- Contract.EndContractBlock();
var task = new Task<TResult>();
bool succeeded = task.TrySetCanceled(exception.CancellationToken, exception);
{
// Check arguments
if (function == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.function);
- Contract.EndContractBlock();
// Short-circuit if we are given a pre-canceled token
if (cancellationToken.IsCancellationRequested)
{
// Check arguments
if (function == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.function);
- Contract.EndContractBlock();
// Short-circuit if we are given a pre-canceled token
if (cancellationToken.IsCancellationRequested)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.millisecondsDelay, ExceptionResource.Task_Delay_InvalidMillisecondsDelay);
}
- Contract.EndContractBlock();
// some short-cuts in case quick completion is in order
if (cancellationToken.IsCancellationRequested)
{
// 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.
// 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);
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);
{
// 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<TResult>(tasks); // small optimization in the case of an empty task array
// Some common logic to support WhenAll<TResult> methods
private static Task<TResult[]> InternalWhenAll<TResult>(Task<TResult>[] 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<TResult[]>(false, new TResult[0], TaskCreationOptions.None, default(CancellationToken)) :
new WhenAllPromise<TResult>(tasks);
internal WhenAllPromise(Task<T>[] 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;
{
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.
public static Task<Task> WhenAny(IEnumerable<Task> 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.
[FriendAccessAllowed]
internal static Task<TResult> CreateUnwrapPromise<TResult>(Task outerTask, bool lookForOce)
{
- Contract.Requires(outerTask != null);
+ Debug.Assert(outerTask != null);
return new UnwrapPromise<TResult>(outerTask, lookForOce);
}
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;
/// <param name="task">The now-completed outer task.</param>
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
/// <returns>true if the transfer was successful; otherwise, false.</returns>
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);
using System;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Security;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.ExceptionServices;
using System.Runtime.CompilerServices;
using System.Threading;
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<Task> || action is Action<Task, object>,
+ Debug.Assert(action is Action<Task> || action is Action<Task, object>,
"Invalid delegate type in ContinuationTaskFromTask");
m_antecedent = antecedent;
}
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<Task, TResult> || function is Func<Task, object, TResult>,
+ Debug.Assert(function is Func<Task, TResult> || function is Func<Task, object, TResult>,
"Invalid delegate type in ContinuationResultTaskFromTask");
m_antecedent = antecedent;
}
Task<TAntecedentResult> 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<Task<TAntecedentResult>> || action is Action<Task<TAntecedentResult>, object>,
+ Debug.Assert(action is Action<Task<TAntecedentResult>> || action is Action<Task<TAntecedentResult>, object>,
"Invalid delegate type in ContinuationTaskFromResultTask");
m_antecedent = antecedent;
}
Task<TAntecedentResult> 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<Task<TAntecedentResult>, TResult> || function is Func<Task<TAntecedentResult>, object, TResult>,
+ Debug.Assert(function is Func<Task<TAntecedentResult>, TResult> || function is Func<Task<TAntecedentResult>, object, TResult>,
"Invalid delegate type in ContinuationResultTaskFromResultTask");
m_antecedent = antecedent;
}
/// </param>
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
/// <param name="scheduler">The scheduler to use for the continuation.</param>
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;
/// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
internal AwaitTaskContinuation(Action action, bool flowExecutionContext)
{
- Contract.Requires(action != null);
+ Debug.Assert(action != null);
m_action = action;
if (flowExecutionContext)
{
/// <returns>The created task.</returns>
protected Task CreateTask(Action<object> 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),
/// <param name="currentTask">A reference to Task.t_currentTask.</param>
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
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
using System.Runtime.ExceptionServices;
using System.Security;
/// <param name="task">The task this holder belongs to.</param>
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();
}
/// </remarks>
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<Exception> ||
exceptionObject is ExceptionDispatchInfo || exceptionObject is IEnumerable<ExceptionDispatchInfo>,
"TaskExceptionHolder.Add(): Expected Exception, IEnumerable<Exception>, ExceptionDispatchInfo, or IEnumerable<ExceptionDispatchInfo>");
/// </remarks>
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.");
/// </remarks>
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;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Threading.Tasks
{
m_defaultContinuationOptions = continuationOptions;
}
- [ContractArgumentValidatorAttribute]
internal static void CheckCreationOptions(TaskCreationOptions creationOptions)
{
// Check for validity of options
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.creationOptions);
}
- Contract.EndContractBlock();
}
/* Properties */
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;
// Performs some logic common to all ContinueWhenAll() overloads
internal static Task<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);
internal CompleteOnCountdownPromise(Task<T>[] 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;
internal static Task<Task<T>[]> CommonCWAllLogic<T>(Task<T>[] tasksCopy)
{
- Contract.Requires(tasksCopy != null);
+ Debug.Assert(tasksCopy != null);
// Create a promise task to be returned to the user
CompleteOnCountdownPromise<T> promise = new CompleteOnCountdownPromise<T>(tasksCopy);
public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
- Contract.EndContractBlock();
return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction, CancellationToken cancellationToken)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
- Contract.EndContractBlock();
return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction, TaskContinuationOptions continuationOptions)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
- Contract.EndContractBlock();
return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
- Contract.EndContractBlock();
return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler);
}
public Task ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>[]> continuationAction)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
- Contract.EndContractBlock();
return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
CancellationToken cancellationToken)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
- Contract.EndContractBlock();
return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
TaskContinuationOptions continuationOptions)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
- Contract.EndContractBlock();
return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
- Contract.EndContractBlock();
return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler);
}
public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
- Contract.EndContractBlock();
return TaskFactory<TResult>.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction, CancellationToken cancellationToken)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
- Contract.EndContractBlock();
return TaskFactory<TResult>.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction, TaskContinuationOptions continuationOptions)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
- Contract.EndContractBlock();
return TaskFactory<TResult>.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
- Contract.EndContractBlock();
return TaskFactory<TResult>.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
}
public Task<TResult> ContinueWhenAll<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
- Contract.EndContractBlock();
return TaskFactory<TResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
CancellationToken cancellationToken)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
- Contract.EndContractBlock();
return TaskFactory<TResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
TaskContinuationOptions continuationOptions)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
- Contract.EndContractBlock();
return TaskFactory<TResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
- Contract.EndContractBlock();
return TaskFactory<TResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
}
public CompleteOnInvokePromise(IList<Task> 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)
// asynchronously (e.g. WhenAny) rather than synchronously (e.g. WaitAny).
internal static Task<Task> CommonCWAnyLogic(IList<Task> 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.)
public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
- Contract.EndContractBlock();
return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction, CancellationToken cancellationToken)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
- Contract.EndContractBlock();
return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction, TaskContinuationOptions continuationOptions)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
- Contract.EndContractBlock();
return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
- Contract.EndContractBlock();
return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler);
}
public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
- Contract.EndContractBlock();
return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction, CancellationToken cancellationToken)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
- Contract.EndContractBlock();
return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
- Contract.EndContractBlock();
return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
- Contract.EndContractBlock();
return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
}
CancellationToken cancellationToken)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
- Contract.EndContractBlock();
return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
TaskContinuationOptions continuationOptions)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
- Contract.EndContractBlock();
return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
- Contract.EndContractBlock();
return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
}
public Task ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>> continuationAction)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
- Contract.EndContractBlock();
return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
CancellationToken cancellationToken)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
- Contract.EndContractBlock();
return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
TaskContinuationOptions continuationOptions)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
- Contract.EndContractBlock();
return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
- Contract.EndContractBlock();
return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler);
}
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++)
throw new ArgumentNullException(nameof(tasks));
if (tasks.Length == 0)
throw new ArgumentException(SR.Task_MultiTaskContinuation_EmptyTaskList, nameof(tasks));
- Contract.EndContractBlock();
Task<TResult>[] tasksCopy = new Task<TResult>[tasks.Length];
for (int i = 0; i < tasks.Length; i++)
}
// Throw an exception if "options" argument specifies illegal options
- [ContractArgumentValidatorAttribute]
internal static void CheckMultiTaskContinuationOptions(TaskContinuationOptions continuationOptions)
{
// Construct a mask to check for illegal options
// Check that no "fire" options are specified.
if ((continuationOptions & NotOnAny) != 0)
throw new ArgumentOutOfRangeException(nameof(continuationOptions), SR.Task_MultiTaskContinuation_FireOptions);
- Contract.EndContractBlock();
}
}
}
using System.Threading;
using System.Security;
using System.Collections.Concurrent;
-using System.Diagnostics.Contracts;
using System.Diagnostics;
using System.Runtime.CompilerServices;
/// </summary>
internal void InternalQueueTask(Task task)
{
- Contract.Requires(task != null);
+ Debug.Assert(task != null);
if (TplEtwProvider.Log.IsEnabled())
{
using System.IO;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Threading.Tasks
{
/// <returns>An IAsyncResult to represent the task's asynchronous operation.</returns>
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.)
/// <param name="asyncResult">The Task used as the IAsyncResult.</param>
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
/// <param name="completedSynchronously">The new CompletedSynchronously value.</param>
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;
using System;
using System.Security;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Collections.Generic;
using System.Text;
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
using System.Security;
using System.Runtime.Versioning;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
internal delegate Object InternalCrossContextDelegate(Object[] args);
{
throw new ArgumentNullException(nameof(start));
}
- Contract.EndContractBlock();
SetStartHelper((Delegate)start, 0); //0 will setup Thread with default stackSize
}
}
if (0 > maxStackSize)
throw new ArgumentOutOfRangeException(nameof(maxStackSize), SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
SetStartHelper((Delegate)start, maxStackSize);
}
public Thread(ParameterizedThreadStart start)
{
throw new ArgumentNullException(nameof(start));
}
- Contract.EndContractBlock();
SetStartHelper((Delegate)start, 0);
}
}
if (0 > maxStackSize)
throw new ArgumentOutOfRangeException(nameof(maxStackSize), SR.ArgumentOutOfRange_NeedNonNegNum);
- Contract.EndContractBlock();
SetStartHelper((Delegate)start, maxStackSize);
}
{
get
{
- Contract.Ensures(Contract.Result<Thread>() != null);
return GetCurrentThreadNative();
}
}
{
get
{
- Contract.Ensures(Contract.Result<CultureInfo>() != null);
return CultureInfo.CurrentUICulture;
}
{
get
{
- Contract.Ensures(Contract.Result<CultureInfo>() != 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.
internal static AppDomain GetDomain()
{
- Contract.Ensures(Contract.Result<AppDomain>() != null);
-
AppDomain ad;
ad = GetFastDomainInternal();
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Threading
{
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;
{
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);
}
{
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);
}
{
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);
}
{
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);
}
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics;
- using System.Diagnostics.Contracts;
using System.Diagnostics.Tracing;
using Microsoft.Win32.SafeHandles;
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);
}
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);
}
{
if (callback == null)
throw new ArgumentNullException(nameof(TimerCallback));
- Contract.EndContractBlock();
m_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, 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);
}
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);
}
{
if (notifyObject == null)
throw new ArgumentNullException(nameof(notifyObject));
- Contract.EndContractBlock();
return m_timer.Close(notifyObject);
}
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;
{
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
- Contract.EndContractBlock();
return WaitOne((long)millisecondsTimeout, exitContext);
}
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic);
}
- Contract.EndContractBlock();
int ret = WaitOneNative(waitableSafeHandle, (uint)millisecondsTimeout, hasThreadAffinity, exitContext);
if (ret == WAIT_ABANDONED)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic);
}
- Contract.EndContractBlock();
long timeout = -1;
int ret = WaitOneNative(safeWaitHandle, (uint)timeout, hasThreadAffinity, false);
{
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
- Contract.EndContractBlock();
WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length];
for (int i = 0; i < waitHandles.Length; i++)
{
{
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
- Contract.EndContractBlock();
WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length];
for (int i = 0; i < waitHandles.Length; i++)
{
{
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,
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()
// 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
{
throw new ArgumentException(SR.Argument_DateTimeHasTimeOfDay, nameof(dateEnd));
}
- Contract.EndContractBlock();
}
void IDeserializationCallback.OnDeserialization(object sender)
{
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)
// 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
public bool IsFixedDateRule => _isFixedDateRule;
- [Pure]
public override bool Equals(object obj) =>
obj is TransitionTime && Equals((TransitionTime)obj);
public static bool operator !=(TransitionTime t1, TransitionTime t2) => !t1.Equals(t2);
- [Pure]
public bool Equals(TransitionTime other) =>
_isFixedDateRule == other._isFixedDateRule &&
_timeOfDay == other._timeOfDay &&
{
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))
{
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)
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Text;
{
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];
{
throw new ArgumentException("bad data", nameof(data));
}
- Contract.EndContractBlock();
Magic = (uint)TZif_ToInt32(data, index + 00);
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;
{
throw new ArgumentException(SR.Argument_DateTimeOffsetIsNotAmbiguous, nameof(dateTimeOffset));
}
- Contract.EndContractBlock();
DateTime adjustedTime = ConvertTime(dateTimeOffset, this).DateTime;
{
throw new ArgumentException(SR.Argument_DateTimeIsNotAmbiguous, nameof(dateTime));
}
- Contract.EndContractBlock();
DateTime adjustedTime;
if (dateTime.Kind == DateTimeKind.Local)
{
throw new ArgumentNullException(nameof(destinationTimeZone));
}
- Contract.EndContractBlock();
// calculate the destination time zone offset
DateTime utcDateTime = dateTimeOffset.UtcDateTime;
{
throw new ArgumentNullException(nameof(destinationTimeZone));
}
- Contract.EndContractBlock();
// Special case to give a way clearing the cache without exposing ClearCachedData()
if (dateTime.Ticks == 0)
{
throw new ArgumentNullException(nameof(destinationTimeZone));
}
- Contract.EndContractBlock();
DateTimeKind sourceKind = cachedData.GetCorrespondingKind(sourceTimeZone);
if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && (dateTime.Kind != DateTimeKind.Unspecified) && (dateTime.Kind != sourceKind))
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidSerializedString, source), nameof(source));
}
- Contract.EndContractBlock();
return StringSerializer.GetDeserializedTimeZoneInfo(source);
}
{
throw new ArgumentNullException(nameof(other));
}
- Contract.EndContractBlock();
// check the utcOffset and supportsDaylightSavingTime members
if (_baseUtcOffset != other._baseUtcOffset ||
{
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)
/// <summary>
/// Helper function that validates the TimeSpan is within +/- 14.0 hours
/// </summary>
- [Pure]
internal static bool UtcOffsetOutOfRange(TimeSpan offset) =>
offset.TotalHours < -14.0 || offset.TotalHours > 14.0;
{
throw new ArgumentException(SR.Argument_TimeSpanHasSeconds, nameof(baseUtcOffset));
}
- Contract.EndContractBlock();
adjustmentRulesSupportDst = false;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
//
using System.Reflection;
using System.Runtime.CompilerServices;
-using System.Diagnostics.Contracts;
using StackCrawlMark = System.Threading.StackCrawlMark;
namespace System
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeType GetTypeFromHandleUnsafe(IntPtr handle);
- [Pure]
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern Type GetTypeFromHandle(RuntimeTypeHandle handle);
#if FEATURE_COMINTEROP
internal bool IsWindowsRuntimeObject
{
- [Pure]
get { return IsWindowsRuntimeObjectImpl(); }
}
internal bool IsExportedToWindowsRuntime
{
- [Pure]
get { return IsExportedToWindowsRuntimeImpl(); }
}
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);
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
-using System.Diagnostics.Contracts;
namespace System
{
using System;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.IO;
using System.Reflection;
using System.Security;
throw new ArgumentNullException(nameof(typeName));
if (typeName.Length > 0 && typeName[0] == '\0')
throw new ArgumentException(SR.Format_StringZeroLength);
- Contract.EndContractBlock();
Type ret = null;
private static Assembly ResolveAssembly(string asmName, Func<AssemblyName, Assembly> assemblyResolver, bool throwOnError, ref StackCrawlMark stackMark)
{
- Contract.Requires(asmName != null && asmName.Length > 0);
+ Debug.Assert(asmName != null && asmName.Length > 0);
Assembly assembly = null;
private static Type ResolveType(Assembly assembly, string[] names, Func<Assembly, string, bool, Type> 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;
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
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);
using System.Globalization;
using System.Runtime.Serialization;
using System.Security;
- using System.Diagnostics.Contracts;
[Serializable]
[CLSCompliant(false)]
{
throw new ArgumentNullException(nameof(info));
}
- Contract.EndContractBlock();
info.AddValue("value", (ulong)_value);
}
public unsafe override String ToString()
{
- Contract.Ensures(Contract.Result<String>() != null);
-
#if BIT64
return ((ulong)_value).ToString(CultureInfo.InvariantCulture);
#else // 32
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System
{
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System
{
{
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)
{
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)
}
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
-using System.Diagnostics.Contracts;
namespace System
{
{
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)
{
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)