Skip to content

Commit

Permalink
Fix CA1805 for unnecessary initialization of fields (#38410)
Browse files Browse the repository at this point in the history
This has three primary benefits:
1. In some cases, in particular for static fields where other static fields have non-default initialization, the C# compiler can't elide the default initialization, resulting in more IL.
2. It highlights places where the field is otherwise unused and can be deleted, but where the presence of the initialization was silencing the C# compiler's warnings about the unused field.
3. It increases consistency and decreases maintenance / code size / etc.
  • Loading branch information
stephentoub committed Jun 26, 2020
1 parent 01a0c00 commit ed78fad
Show file tree
Hide file tree
Showing 571 changed files with 1,699 additions and 1,822 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public static extern bool IsAttached
// desired events are actually reported to the debugger.
//
// Constant representing the default category
public static readonly string? DefaultCategory = null;
public static readonly string? DefaultCategory;

// Posts a message for the attached debugger. If there is no
// debugger attached, has no effect. The debugger may or may not
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ private delegate void GetSourceLineInfoDelegate(Assembly? assembly, string assem
int loadedPeSize, IntPtr inMemoryPdbAddress, int inMemoryPdbSize, int methodToken, int ilOffset,
out string? sourceFile, out int sourceLine, out int sourceColumn);

private static GetSourceLineInfoDelegate? s_getSourceLineInfo = null;
private static GetSourceLineInfoDelegate? s_getSourceLineInfo;

[ThreadStatic]
private static int t_reentrancy;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,10 @@ internal static T[] EnlargeArray<T>(T[] incoming, int requiredSize)
internal int m_localCount;
internal SignatureHelper m_localSignature;

private int m_maxStackSize = 0; // Maximum stack size not counting the exceptions.
private int m_maxStackSize; // Maximum stack size not counting the exceptions.

private int m_maxMidStack = 0; // Maximum stack size for a given basic block.
private int m_maxMidStackCur = 0; // Running count of the maximum stack size for the current basic block.
private int m_maxMidStack; // Maximum stack size for a given basic block.
private int m_maxMidStackCur; // Running count of the maximum stack size for the current basic block.

internal int CurrExcStackCount => m_currExcStackCount;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -847,8 +847,8 @@ private void ParseCA(ConstructorInfo con)
}
}

internal bool m_canBeRuntimeImpl = false;
internal bool m_isDllImport = false;
internal bool m_canBeRuntimeImpl;
internal bool m_isDllImport;

#endregion
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,10 @@ internal static ParameterInfo[] GetParameters(
private int m_tkParamDef;
private MetadataImport m_scope;
private Signature? m_signature;
private volatile bool m_nameIsCached = false;
private readonly bool m_noMetadata = false;
private bool m_noDefaultValue = false;
private MethodBase? m_originalMember = null;
private volatile bool m_nameIsCached;
private readonly bool m_noMetadata;
private bool m_noDefaultValue;
private MethodBase? m_originalMember;
#endregion

#region Internal Properties
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ internal sealed class ThreadHelper
private Delegate _start;
internal CultureInfo? _startCulture;
internal CultureInfo? _startUICulture;
private object? _startArg = null;
private ExecutionContext? _executionContext = null;
private object? _startArg;
private ExecutionContext? _executionContext;

internal ThreadHelper(Delegate start)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ internal sealed class RegisteredWaitHandleSafe : CriticalFinalizerObject
private static IntPtr InvalidHandle => new IntPtr(-1);
private IntPtr registeredWaitHandle = InvalidHandle;
private WaitHandle? m_internalWaitObject;
private bool bReleaseNeeded = false;
private volatile int m_lock = 0;
private bool bReleaseNeeded;
private volatile int m_lock;

internal IntPtr GetHandle() => registeredWaitHandle;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ internal struct Variant
typeof(System.DBNull),
};

internal static readonly Variant Empty = default;
internal static readonly Variant Empty;
internal static readonly Variant Missing = new Variant(Variant.CV_MISSING, Type.Missing, 0);
internal static readonly Variant DBNull = new Variant(Variant.CV_NULL, System.DBNull.Value, 0);

Expand Down
8 changes: 4 additions & 4 deletions src/libraries/Common/src/Interop/Interop.Ldap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ internal sealed class LDAP_TIMEVAL
[StructLayout(LayoutKind.Sequential)]
internal sealed class berval
{
public int bv_len = 0;
public int bv_len;
public IntPtr bv_val = IntPtr.Zero;

public berval() { }
Expand All @@ -129,8 +129,8 @@ public berval() { }
internal sealed class LdapControl
{
public IntPtr ldctl_oid = IntPtr.Zero;
public berval ldctl_value = null;
public bool ldctl_iscritical = false;
public berval ldctl_value;
public bool ldctl_iscritical;

public LdapControl() { }
}
Expand Down Expand Up @@ -161,7 +161,7 @@ internal struct SecPkgContext_IssuerListInfoEx
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal sealed class LdapMod
{
public int type = 0;
public int type;
public IntPtr attribute = IntPtr.Zero;
public IntPtr values = IntPtr.Zero;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ internal sealed class SafeSslHandle : SafeHandle
private SafeBioHandle? _readBio;
private SafeBioHandle? _writeBio;
private bool _isServer;
private bool _handshakeCompleted = false;
private bool _handshakeCompleted;

public GCHandle AlpnHandle;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ internal partial class Advapi32
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal class ENUM_SERVICE_STATUS
{
internal string? serviceName = null;
internal string? displayName = null;
internal int serviceType = 0;
internal int currentState = 0;
internal int controlsAccepted = 0;
internal int win32ExitCode = 0;
internal int serviceSpecificExitCode = 0;
internal int checkPoint = 0;
internal int waitHint = 0;
internal string? serviceName;
internal string? displayName;
internal int serviceType;
internal int currentState;
internal int controlsAccepted;
internal int win32ExitCode;
internal int serviceSpecificExitCode;
internal int checkPoint;
internal int waitHint;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@ internal partial class Advapi32
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal class ENUM_SERVICE_STATUS_PROCESS
{
internal string? serviceName = null;
internal string? displayName = null;
internal int serviceType = 0;
internal int currentState = 0;
internal int controlsAccepted = 0;
internal int win32ExitCode = 0;
internal int serviceSpecificExitCode = 0;
internal int checkPoint = 0;
internal int waitHint = 0;
internal int processID = 0;
internal int serviceFlags = 0;
internal string? serviceName;
internal string? displayName;
internal int serviceType;
internal int currentState;
internal int controlsAccepted;
internal int win32ExitCode;
internal int serviceSpecificExitCode;
internal int checkPoint;
internal int waitHint;
internal int processID;
internal int serviceFlags;
}
}
}
2 changes: 1 addition & 1 deletion src/libraries/Common/src/Interop/Windows/BCrypt/Cng.cs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ protected sealed override bool ReleaseHandle()

internal sealed class SafeKeyHandle : SafeBCryptHandle
{
private SafeAlgorithmHandle? _parentHandle = null;
private SafeAlgorithmHandle? _parentHandle;

public void SetParentHandle(SafeAlgorithmHandle parentHandle)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ namespace System.Net
// _SecPkgInfoW in sspi.h.
internal class SecurityPackageInfoClass
{
internal int Capabilities = 0;
internal short Version = 0;
internal short RPCID = 0;
internal int MaxToken = 0;
internal string? Name = null;
internal string? Comment = null;
internal int Capabilities;
internal short Version;
internal short RPCID;
internal int MaxToken;
internal string? Name;
internal string? Comment;

/*
This is to support SSL with no client cert.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ internal partial class WinHttp
{
internal class SafeWinHttpHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeWinHttpHandle? _parentHandle = null;
private SafeWinHttpHandle? _parentHandle;

public SafeWinHttpHandle() : base(true)
{
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/Common/src/System/CodeDom/CodeObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class CodeObject
internal class CodeObject
#endif
{
private IDictionary _userData = null;
private IDictionary _userData;

public CodeObject() { }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ internal class CodeTypeReference : CodeObject
private string _baseType;
private readonly bool _isInterface;
private CodeTypeReferenceCollection _typeArguments;
private bool _needsFixup = false;
private bool _needsFixup;

public CodeTypeReference()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ internal abstract partial class DbConnectionFactory

// s_pendingOpenNonPooled is an array of tasks used to throttle creation of non-pooled connections to
// a maximum of Environment.ProcessorCount at a time.
private static uint s_pendingOpenNonPooledNext = 0;
private static uint s_pendingOpenNonPooledNext;
private static readonly Task<DbConnectionInternal>[] s_pendingOpenNonPooled = new Task<DbConnectionInternal>[Environment.ProcessorCount];
private static Task<DbConnectionInternal> s_completedTask;

Expand Down
4 changes: 2 additions & 2 deletions src/libraries/Common/src/System/Net/CookieParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,7 @@ private static bool InternalSetNameMethod(Cookie cookie, string? value)
return cookie.InternalSetName(value);
}
#else
private static Func<Cookie, string?, bool>? s_internalSetNameMethod = null;
private static Func<Cookie, string?, bool>? s_internalSetNameMethod;
private static Func<Cookie, string?, bool> InternalSetNameMethod
{
get
Expand All @@ -546,7 +546,7 @@ private static bool InternalSetNameMethod(Cookie cookie, string? value)
}
#endif

private static FieldInfo? s_isQuotedDomainField = null;
private static FieldInfo? s_isQuotedDomainField;
private static FieldInfo IsQuotedDomainField
{
get
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ internal class WinInetProxyHelper
private const int RecentAutoDetectionInterval = 120_000; // 2 minutes in milliseconds.
private readonly string? _autoConfigUrl, _proxy, _proxyBypass;
private readonly bool _autoDetect;
private readonly bool _useProxy = false;
private readonly bool _useProxy;
private bool _autoDetectionFailed;
private int _lastTimeAutoDetectionFailed; // Environment.TickCount units (milliseconds).

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ namespace System.Net.Quic.Implementations.Mock
internal sealed class MockConnection : QuicConnectionProvider
{
private readonly bool _isClient;
private bool _disposed = false;
private bool _disposed;
private IPEndPoint? _remoteEndPoint;
private IPEndPoint? _localEndPoint;
private object _syncObject = new object();
private Socket? _socket = null;
private IPEndPoint? _peerListenEndPoint = null;
private TcpListener? _inboundListener = null;
private Socket? _socket;
private IPEndPoint? _peerListenEndPoint;
private TcpListener? _inboundListener;
private long _nextOutboundBidirectionalStream;
private long _nextOutboundUnidirectionalStream;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ namespace System.Net.Quic.Implementations.Mock
{
internal sealed class MockListener : QuicListenerProvider
{
private bool _disposed = false;
private bool _disposed;
private SslServerAuthenticationOptions? _sslOptions;
private IPEndPoint _listenEndPoint;
private TcpListener _tcpListener;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ namespace System.Net.Quic.Implementations.Mock
{
internal sealed class MockStream : QuicStreamProvider
{
private bool _disposed = false;
private bool _disposed;
private readonly long _streamId;
private bool _canRead;
private bool _canWrite;

private MockConnection? _connection;

private Socket? _socket = null;
private Socket? _socket;

// Constructor for outbound streams
internal MockStream(MockConnection connection, long streamId, bool bidirectional)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace System.Net.Quic.Implementations.MsQuic.Internal
{
internal sealed class MsQuicSession : IDisposable
{
private bool _disposed = false;
private bool _disposed;
private IntPtr _nativeObjPtr;
private bool _opened;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ internal sealed class MsQuicStream : QuicStreamProvider
// Used by the class to indicate that the stream is writable.
private readonly bool _canWrite;

private volatile bool _disposed = false;
private volatile bool _disposed;

private List<QuicBuffer> _receiveQuicBuffers = new List<QuicBuffer>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ internal partial class NTAuthentication
private string? _protocolName;
private string? _clientSpecifiedSpn;

private ChannelBinding? _channelBinding = null;
private ChannelBinding? _channelBinding;

// If set, no more calls should be made.
internal bool IsCompleted => _isCompleted;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ internal sealed class SafeFreeSslCredentials : SafeFreeCredentials
private SafeEvpPKeyHandle? _certKeyHandle;
private SslProtocols _protocols = SslProtocols.None;
private EncryptionPolicy _policy;
private bool _isInvalid = false;
private bool _isInvalid;

internal SafeX509Handle? CertHandle
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public static ManagedWebSocket CreateFromConnectedStream(
/// expect to always receive unmasked payloads, whereas servers always send
/// unmasked payloads and expect to always receive masked payloads.
/// </summary>
private readonly bool _isServer = false;
private readonly bool _isServer;
/// <summary>The agreed upon subprotocol with the server.</summary>
private readonly string? _subprotocol;
/// <summary>Timer used to send periodic pings to the server, at the interval specified</summary>
Expand Down Expand Up @@ -104,9 +104,9 @@ public static ManagedWebSocket CreateFromConnectedStream(
/// <summary>Whether we've ever received a close frame.</summary>
private bool _receivedCloseFrame;
/// <summary>The reason for the close, as sent by the server, or null if not yet closed.</summary>
private WebSocketCloseStatus? _closeStatus = null;
private WebSocketCloseStatus? _closeStatus;
/// <summary>A description of the close reason as sent by the server, or null if not yet closed.</summary>
private string? _closeStatusDescription = null;
private string? _closeStatusDescription;

/// <summary>
/// The last header received in a ReceiveAsync. If ReceiveAsync got a header but then
Expand All @@ -118,15 +118,15 @@ public static ManagedWebSocket CreateFromConnectedStream(
/// </summary>
private MessageHeader _lastReceiveHeader = new MessageHeader { Opcode = MessageOpcode.Text, Fin = true };
/// <summary>The offset of the next available byte in the _receiveBuffer.</summary>
private int _receiveBufferOffset = 0;
private int _receiveBufferOffset;
/// <summary>The number of bytes available in the _receiveBuffer.</summary>
private int _receiveBufferCount = 0;
private int _receiveBufferCount;
/// <summary>
/// When dealing with partially read fragments of binary/text messages, a mask previously received may still
/// apply, and the first new byte received may not correspond to the 0th position in the mask. This value is
/// the next offset into the mask that should be applied.
/// </summary>
private int _receivedMaskOffsetOffset = 0;
private int _receivedMaskOffsetOffset;
/// <summary>
/// Temporary send buffer. This should be released back to the ArrayPool once it's
/// no longer needed for the current send operation. It is stored as an instance
Expand Down
Loading

0 comments on commit ed78fad

Please sign in to comment.