Skip to content

Commit

Permalink
Use ArgumentNullException.ThrowIfNull and ObjectDisposedException.Thr…
Browse files Browse the repository at this point in the history
…owIf in more places (#79096)
  • Loading branch information
stephentoub authored Dec 2, 2022
1 parent bcc818f commit 042d3ee
Show file tree
Hide file tree
Showing 56 changed files with 133 additions and 334 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,7 @@ public static bool IsEntered(object obj)
[UnsupportedOSPlatform("browser")]
public static bool Wait(object obj, int millisecondsTimeout)
{
if (obj == null)
throw (new ArgumentNullException(nameof(obj)));
ArgumentNullException.ThrowIfNull(obj);
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,7 @@ internal static void ThrowIfInvalidState(WebSocketState currentState, bool isDis
if (currentState == validState)
{
// Ordering is important to maintain .NET 4.5 WebSocket implementation exception behavior.
if (isDisposed)
{
throw new ObjectDisposedException(nameof(WebSocket));
}

ObjectDisposedException.ThrowIf(isDisposed, typeof(WebSocket));
return;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,6 @@
<data name="Partitioner_DynamicPartitionsNotSupported" xml:space="preserve">
<value>Dynamic partitions are not supported by this partitioner.</value>
</data>
<data name="PartitionerStatic_CanNotCallGetEnumeratorAfterSourceHasBeenDisposed" xml:space="preserve">
<value>Can not call GetEnumerator on partitions after the source enumerable is disposed</value>
</data>
<data name="PartitionerStatic_CurrentCalledBeforeMoveNext" xml:space="preserve">
<value>MoveNext must be called at least once before calling Current.</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -605,15 +605,10 @@ internal InternalPartitionEnumerable(IEnumerator<TSource> sharedReader, bool use

public IEnumerator<KeyValuePair<long, TSource>> GetEnumerator()
{
if (_disposed)
{
throw new ObjectDisposedException(SR.PartitionerStatic_CanNotCallGetEnumeratorAfterSourceHasBeenDisposed);
}
else
{
return new InternalPartitionEnumerator(_sharedReader, _sharedIndex,
_hasNoElementsLeft, _activePartitionCount, this, _useSingleChunking);
}
ObjectDisposedException.ThrowIf(_disposed, this);

return new InternalPartitionEnumerator(_sharedReader, _sharedIndex,
_hasNoElementsLeft, _activePartitionCount, this, _useSingleChunking);
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -524,8 +524,7 @@ public IEnumerable<T> this[string expandedName]
{
get
{
if (expandedName == null)
throw new ArgumentNullException(nameof(expandedName));
ArgumentNullException.ThrowIfNull(expandedName);
if (name == null)
{
name = expandedName;
Expand Down Expand Up @@ -559,8 +558,7 @@ public T? this[string expandedName]
{
get
{
if (expandedName == null)
throw new ArgumentNullException(nameof(expandedName));
ArgumentNullException.ThrowIfNull(expandedName);
if (name == null)
{
name = expandedName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ public virtual void AddService(Type serviceType, object serviceInstance, bool pr
// We're going to add this locally. Ensure that the service instance
// is correct.
//
if (serviceType == null) throw new ArgumentNullException(nameof(serviceType));
if (serviceInstance == null) throw new ArgumentNullException(nameof(serviceInstance));
ArgumentNullException.ThrowIfNull(serviceType);
ArgumentNullException.ThrowIfNull(serviceInstance);
if (!(serviceInstance is ServiceCreatorCallback) && !serviceInstance.GetType().IsCOMObject && !serviceType.IsInstanceOfType(serviceInstance))
{
throw new ArgumentException(SR.Format(SR.ErrorInvalidServiceInstance, serviceType.FullName));
Expand Down Expand Up @@ -119,8 +119,8 @@ public virtual void AddService(Type serviceType, ServiceCreatorCallback callback
// We're going to add this locally. Ensure that the service instance
// is correct.
//
if (serviceType == null) throw new ArgumentNullException(nameof(serviceType));
if (callback == null) throw new ArgumentNullException(nameof(callback));
ArgumentNullException.ThrowIfNull(serviceType);
ArgumentNullException.ThrowIfNull(callback);

if (Services.ContainsKey(serviceType))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -956,14 +956,8 @@ protected override void OnValueChanged(object? component, EventArgs e)
/// </summary>
public override void RemoveValueChanged(object? component, EventHandler handler)
{
if (component == null)
{
throw new ArgumentNullException(nameof(component));
}
if (handler == null)
{
throw new ArgumentNullException(nameof(handler));
}
ArgumentNullException.ThrowIfNull(component);
ArgumentNullException.ThrowIfNull(handler);

// If there's an event called <propertyname>Changed, we hooked the caller's
// handler directly up to that on the component, so remove it now.
Expand Down
19 changes: 8 additions & 11 deletions src/libraries/System.Console/src/System/Console.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public static Encoding InputEncoding
}
set
{
CheckNonNull(value, nameof(value));
ArgumentNullException.ThrowIfNull(value);

lock (s_syncObject)
{
Expand Down Expand Up @@ -127,7 +127,7 @@ public static Encoding OutputEncoding
[UnsupportedOSPlatform("tvos")]
set
{
CheckNonNull(value, nameof(value));
ArgumentNullException.ThrowIfNull(value);

lock (s_syncObject)
{
Expand Down Expand Up @@ -705,7 +705,8 @@ public static Stream OpenStandardError(int bufferSize)
[UnsupportedOSPlatform("tvos")]
public static void SetIn(TextReader newIn)
{
CheckNonNull(newIn, nameof(newIn));
ArgumentNullException.ThrowIfNull(newIn);

newIn = SyncTextReader.GetSynchronizedTextReader(newIn);
lock (s_syncObject)
{
Expand All @@ -715,7 +716,8 @@ public static void SetIn(TextReader newIn)

public static void SetOut(TextWriter newOut)
{
CheckNonNull(newOut, nameof(newOut));
ArgumentNullException.ThrowIfNull(newOut);

newOut = TextWriter.Synchronized(newOut);
lock (s_syncObject)
{
Expand All @@ -726,7 +728,8 @@ public static void SetOut(TextWriter newOut)

public static void SetError(TextWriter newError)
{
CheckNonNull(newError, nameof(newError));
ArgumentNullException.ThrowIfNull(newError);

newError = TextWriter.Synchronized(newError);
lock (s_syncObject)
{
Expand All @@ -735,12 +738,6 @@ public static void SetError(TextWriter newError)
}
}

private static void CheckNonNull(object obj, string paramName)
{
if (obj == null)
throw new ArgumentNullException(paramName);
}

//
// Give a hint to the code generator to not inline the common console methods. The console methods are
// not performance critical. It is unnecessary code bloat to have them inlined.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -297,8 +297,7 @@ public long Read(long offset, byte[] buffer, int offsetInBuffer, int count)
throw new SqlNullValueException();

// Validate the arguments
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
ArgumentNullException.ThrowIfNull(buffer);

if (offset > Length || offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
Expand Down Expand Up @@ -343,8 +342,7 @@ public void Write(long offset, byte[] buffer, int offsetInBuffer, int count)
else
{
// Validate the arguments
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
ArgumentNullException.ThrowIfNull(buffer);

if (_rgbBuf == null)
throw new SqlTypeException(SR.SqlMisc_NoBufferMessage);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -294,8 +294,7 @@ public long Read(long offset, char[] buffer, int offsetInBuffer, int count)
throw new SqlNullValueException();

// Validate the arguments
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
ArgumentNullException.ThrowIfNull(buffer);

if (offset > Length || offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
Expand Down Expand Up @@ -341,8 +340,7 @@ public void Write(long offset, char[] buffer, int offsetInBuffer, int count)
else
{
// Validate the arguments
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
ArgumentNullException.ThrowIfNull(buffer);

if (_rgchBuf == null)
throw new SqlTypeException(SR.SqlMisc_NoBufferMessage);
Expand Down Expand Up @@ -650,8 +648,7 @@ public int Read(char[] buffer, int offset, int count)
{
CheckIfStreamClosed();

if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
ArgumentNullException.ThrowIfNull(buffer);
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > buffer.Length - offset)
Expand All @@ -667,8 +664,7 @@ public void Write(char[] buffer, int offset, int count)
{
CheckIfStreamClosed();

if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
ArgumentNullException.ThrowIfNull(buffer);
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > buffer.Length - offset)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -579,9 +579,8 @@ public SqlDecimal(long value)
public SqlDecimal(byte bPrecision, byte bScale, bool fPositive, int[] bits)
{
CheckValidPrecScale(bPrecision, bScale);
if (bits == null)
throw new ArgumentNullException(nameof(bits));
else if (bits.Length != 4)
ArgumentNullException.ThrowIfNull(bits);
if (bits.Length != 4)
throw new ArgumentException(SQLResource.InvalidArraySizeMessage, nameof(bits));

_bPrec = bPrecision;
Expand Down Expand Up @@ -987,8 +986,7 @@ public override string ToString()

public static SqlDecimal Parse(string s)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
ArgumentNullException.ThrowIfNull(s);

if (s == SQLResource.NullString)
return SqlDecimal.Null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -395,8 +395,7 @@ public override int Read(byte[] buffer, int offset, int count)
ThrowIfStreamClosed(nameof(Read));
ThrowIfStreamCannotRead(nameof(Read));

if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
ArgumentNullException.ThrowIfNull(buffer);
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > buffer.Length - offset)
Expand Down Expand Up @@ -432,8 +431,7 @@ public override void Write(byte[] buffer, int offset, int count)
ThrowIfStreamClosed(nameof(Write));
ThrowIfStreamCannotWrite(nameof(Write));

if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
ArgumentNullException.ThrowIfNull(buffer);
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > buffer.Length - offset)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@ public string Source
[MemberNotNull(nameof(_src))]
set
{
if (value == null)
throw new ArgumentNullException(nameof(Source));
ArgumentNullException.ThrowIfNull(value, nameof(Source));
_src = value;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,7 @@ public Type SwitchType
[MemberNotNull(nameof(_type))]
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
ArgumentNullException.ThrowIfNull(value);
_type = value;
}
}
Expand All @@ -49,8 +48,7 @@ public Type SwitchType
[RequiresUnreferencedCode("Types may be trimmed from the assembly.")]
public static SwitchAttribute[] GetAll(Assembly assembly)
{
if (assembly == null)
throw new ArgumentNullException(nameof(assembly));
ArgumentNullException.ThrowIfNull(assembly);

List<object> switchAttribs = new List<object>();
object[] attribs = assembly.GetCustomAttributes(typeof(SwitchAttribute), false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ public Type SwitchLevelType
[MemberNotNull(nameof(_type))]
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
ArgumentNullException.ThrowIfNull(value);

_type = value;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -534,8 +534,7 @@ public SourceSwitch Switch
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(Switch));
ArgumentNullException.ThrowIfNull(value, nameof(Switch));

Initialize();
_internalSwitch = value;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ public long MaxRequestContentBufferSize
HttpContent.MaxBufferSize));
}

CheckDisposed();
ObjectDisposedException.ThrowIf(_disposed, this);

// No-op on property setter.
}
Expand Down Expand Up @@ -751,14 +751,6 @@ private void ThrowForModifiedManagedSslOptionsIfStarted()
_socketHandler!.SslOptions = _socketHandler!.SslOptions;
}

private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().ToString());
}
}

private object InvokeNativeHandlerMethod(string name, params object?[] parameters)
{
MethodInfo? method;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ public long MaxRequestContentBufferSize
HttpContent.MaxBufferSize));
}

CheckDisposed();
ObjectDisposedException.ThrowIf(_disposed, this);

// No-op on property setter.
}
Expand Down Expand Up @@ -327,13 +327,5 @@ private void ThrowForModifiedManagedSslOptionsIfStarted()
// SslOptions is changed, since SslOptions itself does not do any such checks.
_underlyingHandler.SslOptions = _underlyingHandler.SslOptions;
}

private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().ToString());
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -160,10 +160,7 @@ private int TryRequestCreditNoLock(int amount)
{
Debug.Assert(Monitor.IsEntered(SyncObject), "Shouldn't be called outside lock.");

if (_disposed)
{
throw new ObjectDisposedException($"{nameof(CreditManager)}:{_owner.GetType().Name}:{_name}");
}
ObjectDisposedException.ThrowIf(_disposed, this);

if (_current > 0)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1396,11 +1396,7 @@ private void ThrowEOFUnexpected()
// The connection closed before we were able to read everything we needed.
// If it was due to us being disposed, fail with the correct exception.
// Otherwise, it was due to the connection being closed and it wasn't expected.
if (_disposed)
{
throw new ObjectDisposedException(nameof(WebSocket));
}

ObjectDisposedException.ThrowIf(_disposed, typeof(WebSocket));
throw new WebSocketException(WebSocketError.ConnectionClosedPrematurely);
}

Expand Down
Loading

0 comments on commit 042d3ee

Please sign in to comment.