Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate an array type in a Roslyn code generator?

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?

like image 893
Benjamin Hodgson Avatar asked Jan 20 '26 03:01

Benjamin Hodgson


1 Answers

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.

like image 199
Benjamin Hodgson Avatar answered Jan 21 '26 16:01

Benjamin Hodgson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!