I want to generate a method with a return type of Foo[]
. My code looks roughly like this (with using static SyntaxFactory
):
var methodDecl = MethodDeclaration(
returnType: ArrayType(IdentifierName("Foo")),
identifier: Identifier("Bar"),
parameterList: ParameterList(),
body: Block(ReturnStatement(LiteralExpression(SyntaxKind.NullLiteralExpression))),
// ...
);
When I execute my refactoring in the debug Visual Studio window, it doesn't generate the []
part of the Foo[]
type:
Foo Bar()
{
return null;
}
How do I make it generate an actual Foo[]
type?
The []
part of the array type is called a rank specifier. The rank specifier describes the size and dimensionality of the array, à la int[10,3][12]
.
The ArrayType
factory method creates an ArrayTypeSyntax
with no RankSpecifiers
at all. To generate the commonly-used Foo[]
syntax, you need to give it a single empty rank specifier.
ArrayType(IdentifierName("Foo"), SingletonList(ArrayRankSpecifier()))
Seems like a bit of a silly default to me, since 1D arrays are by far the most common. As far as I know this isn't documented anywhere.