Skip to content

Commit

Permalink
Use [MemberNotNull] to reduce use of = null!;
Browse files Browse the repository at this point in the history
  • Loading branch information
stephentoub committed Jun 9, 2020
1 parent dab906f commit f64a574
Show file tree
Hide file tree
Showing 42 changed files with 253 additions and 214 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,14 @@ namespace System.Net
//
internal abstract class DebugCriticalHandleMinusOneIsInvalid : CriticalHandleMinusOneIsInvalid
{
private string _trace = null!;
private string _trace;

protected DebugCriticalHandleMinusOneIsInvalid() : base()
{
Trace();
}

private void Trace()
{
_trace = "WARNING! GC-ed >>" + this.GetType().FullName + "<< (should be explicitly closed) \r\n";
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Creating SafeHandle");
#if TRACE_VERBOSE
string stacktrace = Environment.StackTrace;
_trace += stacktrace;
_trace += Environment.StackTrace;
#endif //TRACE_VERBOSE
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,14 @@ namespace System.Net
//
internal abstract class DebugCriticalHandleZeroOrMinusOneIsInvalid : CriticalHandleZeroOrMinusOneIsInvalid
{
private string _trace = null!;
private string _trace;

protected DebugCriticalHandleZeroOrMinusOneIsInvalid() : base()
{
Trace();
}

private void Trace()
{
_trace = "WARNING! GC-ed >>" + this.GetType().FullName + "<< (should be explicitly closed) \r\n";
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Creating SafeHandle");
#if TRACE_VERBOSE
string stacktrace = Environment.StackTrace;
_trace += stacktrace;
_trace += Environment.StackTrace;
#endif //TRACE_VERBOSE
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,14 @@ namespace System.Net
//
internal abstract class DebugSafeHandleMinusOneIsInvalid : SafeHandleMinusOneIsInvalid
{
private string _trace = null!; // initialized by helper called from ctor
private string _trace;

protected DebugSafeHandleMinusOneIsInvalid(bool ownsHandle) : base(ownsHandle)
{
Trace();
}

private void Trace()
{
_trace = "WARNING! GC-ed >>" + this.GetType().FullName + "<< (should be explicitly closed) \r\n";
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Creating SafeHandle");
#if TRACE_VERBOSE
string stacktrace = Environment.StackTrace;
_trace += stacktrace;
_trace += Environment.StackTrace;
#endif //TRACE_VERBOSE
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ internal partial class NTAuthentication
private ContextFlagsPal _contextFlags;

private bool _isCompleted;
private string _package = null!;
private string _package;
private string? _lastProtocolName;
private string? _protocolName;
private string? _clientSpecifiedSpn;
Expand Down Expand Up @@ -98,6 +98,7 @@ internal NTAuthentication(bool isServer, string package, NetworkCredential crede
Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding);
}

[MemberNotNull(nameof(_package))]
private void Initialize(bool isServer, string package, NetworkCredential credential, string? spn, ContextFlagsPal requestedContextFlags, ChannelBinding? channelBinding)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, package, spn, requestedContextFlags);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,14 @@ namespace System.Collections.Concurrent
[DebuggerDisplay("Count = {Count}, Type = {_collection}")]
public class BlockingCollection<T> : IEnumerable<T>, ICollection, IDisposable, IReadOnlyCollection<T>
{
private IProducerConsumerCollection<T> _collection = null!;
private IProducerConsumerCollection<T> _collection;
private int _boundedCapacity;
private const int NON_BOUNDED = -1;
private SemaphoreSlim? _freeNodes;
private SemaphoreSlim _occupiedNodes = null!;
private SemaphoreSlim _occupiedNodes;
private bool _isDisposed;
private CancellationTokenSource _consumersCancellationTokenSource = null!;
private CancellationTokenSource _producersCancellationTokenSource = null!;
private CancellationTokenSource _consumersCancellationTokenSource;
private CancellationTokenSource _producersCancellationTokenSource;

private volatile int _currentAdders;
private const int COMPLETE_ADDING_ON_MASK = unchecked((int)0x80000000);
Expand Down Expand Up @@ -211,6 +211,10 @@ public BlockingCollection(IProducerConsumerCollection<T> collection)
/// <param name="collection">The collection to use as the underlying data store.</param>
/// <param name="boundedCapacity">The bounded size of the collection.</param>
/// <param name="collectionCount">The number of items currently in the underlying collection.</param>
[MemberNotNull(nameof(_collection))]
[MemberNotNull(nameof(_consumersCancellationTokenSource))]
[MemberNotNull(nameof(_producersCancellationTokenSource))]
[MemberNotNull(nameof(_occupiedNodes))]
private void Initialize(IProducerConsumerCollection<T> collection, int boundedCapacity, int collectionCount)
{
Debug.Assert(boundedCapacity > 0 || boundedCapacity == NON_BOUNDED);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

#pragma warning disable 618 // obsolete types, namely IHashCodeProvider

using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.Serialization;

Expand All @@ -24,9 +25,9 @@ namespace System.Collections.Specialized
public abstract class NameObjectCollectionBase : ICollection, ISerializable, IDeserializationCallback
{
private bool _readOnly = false;
private ArrayList _entriesArray = null!; // initialized in Reset method, called from constructor
private ArrayList _entriesArray;
private IEqualityComparer _keyComparer;
private volatile Hashtable _entriesTable = null!; // initialized in Reset method, called from constructor
private volatile Hashtable _entriesTable;
private volatile NameObjectEntry? _nullKeyEntry;
private KeysCollection? _keys;
private int _version;
Expand Down Expand Up @@ -96,6 +97,8 @@ public virtual void OnDeserialization(object? sender)
// Private helpers
//

[MemberNotNull(nameof(_entriesArray))]
[MemberNotNull(nameof(_entriesTable))]
private void Reset()
{
_entriesArray = new ArrayList();
Expand All @@ -104,6 +107,8 @@ private void Reset()
_version++;
}

[MemberNotNull(nameof(_entriesArray))]
[MemberNotNull(nameof(_entriesTable))]
private void Reset(int capacity)
{
_entriesArray = new ArrayList(capacity);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public class AssemblyCatalog : ComposablePartCatalog, ICompositionElement
{
private readonly object _thisLock = new object();
private readonly ICompositionElement _definitionOrigin;
private volatile Assembly _assembly = null!; // Always initiialized with helper
private volatile Assembly _assembly;
private volatile ComposablePartCatalog? _innerCatalog = null;
private int _isDisposed = 0;

Expand Down Expand Up @@ -387,6 +387,7 @@ public AssemblyCatalog(Assembly assembly, ICompositionElement definitionOrigin)
_definitionOrigin = definitionOrigin;
}

[MemberNotNull(nameof(_assembly))]
private void InitializeAssemblyCatalog(Assembly assembly)
{
if (assembly.ReflectionOnly)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,16 @@ namespace System.ComponentModel.Composition.Hosting
public partial class DirectoryCatalog : ComposablePartCatalog, INotifyComposablePartCatalogChanged, ICompositionElement
{
private readonly Lock _thisLock = new Lock();
private readonly ICompositionElement? _definitionOrigin = null;
private ComposablePartCatalogCollection _catalogCollection = null!; // Always initialized with Initialize()
private Dictionary<string, AssemblyCatalog> _assemblyCatalogs = null!;
private volatile bool _isDisposed = false;
private string _path = null!;
private string _fullPath = null!;
private string _searchPattern = null!;
private ReadOnlyCollection<string> _loadedFiles = null!;
private readonly ICompositionElement? _definitionOrigin;
private ComposablePartCatalogCollection _catalogCollection;
private Dictionary<string, AssemblyCatalog> _assemblyCatalogs;
private volatile bool _isDisposed;
private string _path;
private string _fullPath;
private string _searchPattern;
private ReadOnlyCollection<string> _loadedFiles;

private readonly ReflectionContext? _reflectionContext = null;
private readonly ReflectionContext? _reflectionContext;

/// <summary>
/// Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the *.dll files
Expand Down Expand Up @@ -745,6 +745,12 @@ private static string GetFullPath(string path)
return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? fullPath.ToUpperInvariant() : fullPath;
}

[MemberNotNull(nameof(_path))]
[MemberNotNull(nameof(_fullPath))]
[MemberNotNull(nameof(_searchPattern))]
[MemberNotNull(nameof(_assemblyCatalogs))]
[MemberNotNull(nameof(_catalogCollection))]
[MemberNotNull(nameof(_loadedFiles))]
private void Initialize(string path, string searchPattern)
{
_path = path;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ internal class ImportType

private readonly Type _type;
private readonly bool _isAssignableCollectionType;
private Type _contractType = null!; // Initialized in Initialize()
private Type _contractType;
private Func<Export, object>? _castSingleValue;
private readonly bool _isOpenGeneric = false;

Expand Down Expand Up @@ -129,6 +129,7 @@ public static bool IsDescendentOf(Type type, Type baseType)
return IsGenericDescendentOf(type, baseType.GetGenericTypeDefinition());
}

[MemberNotNull(nameof(_contractType))]
private void Initialize(Type type)
{
if (!type.IsGenericType)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public partial class Activity : IDisposable
/// reasonable, but arguments (e.g. specific accounts etc), should not be in
/// the name but rather in the tags.
/// </summary>
public string OperationName { get; } = null!;
public string OperationName { get; }

/// <summary>Gets or sets the display name of the Activity</summary>
/// <remarks>
Expand Down Expand Up @@ -334,7 +334,6 @@ public Activity(string operationName)
if (string.IsNullOrEmpty(operationName))
{
NotifyError(new ArgumentException(SR.OperationNameInvalid));
return;
}

OperationName = operationName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
===========================================================*/

using System;
using System.Diagnostics;

namespace Microsoft.Win32.SafeHandles
{
Expand All @@ -24,7 +25,7 @@ public sealed partial class SafeProcessHandle : SafeHandleZeroOrMinusOneIsInvali
// Process.{Safe}Handle to initalize and use a WaitHandle to successfully use it on
// Unix as well to wait for the process to complete.

private readonly SafeWaitHandle _handle = null!;
private readonly SafeWaitHandle? _handle;
private readonly bool _releaseRef;

internal SafeProcessHandle(int processId, SafeWaitHandle handle) :
Expand All @@ -41,6 +42,7 @@ protected override bool ReleaseHandle()
{
if (_releaseRef)
{
Debug.Assert(_handle != null);
_handle.DangerousRelease();
}
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Threading;
Expand Down Expand Up @@ -192,19 +193,22 @@ private Dictionary<int, string> GetStringTable(bool isHelp)
internal class PerformanceMonitor
{
#if FEATURE_REGISTRY
private RegistryKey _perfDataKey = null!; // will be initialized by Init() method
private RegistryKey _perfDataKey;
#endif
private readonly string _machineName;

internal PerformanceMonitor(string machineName)
{
_machineName = machineName;
#if FEATURE_REGISTRY
Init();
#endif
}

#if FEATURE_REGISTRY
[MemberNotNull(nameof(_perfDataKey))]
private void Init()
{
#if FEATURE_REGISTRY
if (ProcessManager.IsRemoteMachine(_machineName))
{
_perfDataKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.PerformanceData, _machineName);
Expand All @@ -213,8 +217,8 @@ private void Init()
{
_perfDataKey = Registry.PerformanceData;
}
#endif
}
#endif

// Win32 RegQueryValueEx for perf data could deadlock (for a Mutex) up to 2mins in some
// scenarios before they detect it and exit gracefully. In the mean time, ERROR_BUSY,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@

using System;
using System.Collections;
using System.Diagnostics.CodeAnalysis;

namespace System.Diagnostics
{
public class SourceFilter : TraceFilter
{
private string _src = null!;
private string _src;

public SourceFilter(string source)
{
Expand All @@ -31,6 +32,7 @@ public string Source
{
return _src;
}
[MemberNotNull(nameof(_src))]
set
{
if (value == null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@
// 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;
using System.Reflection;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;

namespace System.Diagnostics
{
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Constructor |
AttributeTargets.Event | AttributeTargets.Method | AttributeTargets.Property)]
public sealed class SwitchAttribute : Attribute
{
private Type _type = null!; // Initialized using property
private string _name = null!;
private Type _type;
private string _name;

public SwitchAttribute(string switchName, Type switchType)
{
Expand All @@ -24,6 +24,7 @@ public SwitchAttribute(string switchName, Type switchType)
public string SwitchName
{
get { return _name; }
[MemberNotNull(nameof(_name))]
set
{
if (value == null)
Expand All @@ -38,6 +39,7 @@ public string SwitchName
public Type SwitchType
{
get { return _type; }
[MemberNotNull(nameof(_type))]
set
{
if (value == null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@
// 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.CodeAnalysis;

namespace System.Diagnostics
{
[AttributeUsage(AttributeTargets.Class)]
public sealed class SwitchLevelAttribute : Attribute
{
private Type _type = null!;
private Type _type;

public SwitchLevelAttribute(Type switchLevelType)
{
Expand All @@ -17,6 +19,7 @@ public SwitchLevelAttribute(Type switchLevelType)
public Type SwitchLevelType
{
get { return _type; }
[MemberNotNull(nameof(_type))]
set
{
if (value == null)
Expand Down
Loading

0 comments on commit f64a574

Please sign in to comment.