Skip to content

Supress assignment of default value to field/property declarations #9

@giggio

Description

@giggio

In this cases:

private class C
{
    private bool aBool = false;
    private int i = 0;
    private DateTime d = DateTime.MinValue;
    private MyClass mc = null;
    private MyStruct ms = default(MyStruct);
    //etc...
}

Becomes:

private class C
{
    private bool aBool;
    private int;
    private DateTime d;
    private MyClass mc;
    private MyStruct ms;
    //etc...
}

This analyzer applies to all fields which are not marked const. For each field f, let T be the declared type of f. If f is initialized with the value default(T), then report this diagnostic. The following additional cases should be handled:

  1. If T is a reference type or a nullable value type, then treat null the same as default(T). Note: this means you can always report this diagnostic for f = null, regardless of the actual type T.
  2. If T is a numeric primitive type, then treat 0 (or equivalent double or float) value as default(T).
  3. If T is an enum type, then treat 0 as equivalent to default(T). Note: do NOT treat an enum member this way, even if the value of the enum member is 0.
  4. If T is IntPtr, then treat IntPtr.Zero equivalent to default(T).
  5. If T is UIntPtr, then treat UIntPtr.Zero equivalent to default(T).
  6. If T is DateTime, then treat DateTime.MinValue equivalent to default(T).

Should use WellKnownDiagnosticTags.Unnecessary.

Severity: Info.
Diagnostic id is CC0034.
Category: Usage

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions