RedundantTypedArrayCreation

RedundantTypedArrayCreation

Summary

Use an implicitly-typed array creation instead of an explicitly-typed one.

Default severity

Warning

Description

Specifying the explicit type of the array creation is redundant if the type of the array instance is inferred from the elements specified in the array initializer. Note that [1]:

You can create an implicitly-typed array in which the type of the array instance is inferred from the elements specified in the array initializer.

Remarks

There are some cases where type inference does not work so that the implicitly-typed arrays are not available. For example, when all the elements are Method References, the implicitly-typed array creation causes an error CS0826 as follows:

public static void RaiseCS0826()
{
    _ = new[]
    {
        DoSomething,
    };
}

public static void DoSomething()
{
}

See errors

Code fix

The code fix provides an option removing the explicit type of the array.

Example

Diagnostic

public void Method()
{
    var all = new string[] { "a", "b", "c", };
    ⋮
}

Code fix

public void Method()
{
    var all = new[] { "a", "b", "c", };
    ⋮
}

References

[1] Microsoft, Implicitly Typed Arrays (C# Programming Guide)