Use an implicitly typed array creation instead of an explicitly typed one.
Warning
Specifying the explicit type of the array creation is redundant if the type of the array instance can be 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.
There are some cases where type inference does not work so that the implicitly typed arrays are not available. For example, it doesn't work when all elements are one of the following:
- Target-typed
newexpression [2] (new(…)) - Collection expression (
[…]) nullliteraldefaultliteral
There are also some cases where the implicitly typed arrays change the meaning.
For example, the element of array is of type int? (Nullable<int>) in the
following code:
var array = new int?[] { 42, };Let's leave the array initializer and remove int? from the code. Then, the
element of array is of type int, as follows:
var array = new[] { 42, };Before C# 10, the implicitly typed array creation causes an error CS0826 when all elements are Method References as follows:
public static void RaiseCS0826()
{
_ = new[]
{
DoSomething,
};
}
public static void DoSomething()
{
}This analyzer ignores the explicitly typed arrays where all the elements are Method References in C# 9 and earlier.
In some cases, it is a good idea to create explicitly typed arrays. For example:
var array = new[]
{
new Foo(1),
new Foo(2),
};If it is desirable to describe Foo less often, you can refactor this code as
follows:
var array = new Foo[]
{
new(1),
new(2),
};In most cases, collection expressions are preferable to implicitly typed array creations:
// Collection expression
public IEnumerable<string> GetStrings() => ["foo", "bar"];// Implicitly typed array creation
public IEnumerable<string> GetStrings() => new[] {"foo", "bar"};The code fix provides an option removing the explicit type of the array.
public void Method()
{
var all = new string[] { "a", "b", "c", };
⋮
}public void Method()
{
var all = new[] { "a", "b", "c", };
⋮
}[1] Microsoft, Implicitly Typed Arrays, C# language reference
[2] Microsoft, Target-typed new expressions, C# language reference
