Search code examples
vb.netcode-generationroslynmicrosoft.codeanalysis

How to add As Clause (type) to a property created with SyntaxFactory?


I am creating a property with SyntaxFactory (roslyn)

Dim [property] = SyntaxFactory .PropertyStatement("MyProperty").AddModifiers(SyntaxFactory .Token(SyntaxKind.FriendKeyword))

The result is

Friend Property MyProperty

To add the property type I probably need to use WithAsClause, but I can't find any usable example.


Solution

  • Finally I managed to find an example in Syntax Factory Tests:TestSpacingOnNullableDatetimeType and a solution is

    Dim [property] = SyntaxFactory.PropertyStatement("MyProperty").AddModifiers(SyntaxFactory.Token(SyntaxKind.FriendKeyword)).
                WithAsClause(SyntaxFactory.SimpleAsClause(
                SyntaxFactory.PredefinedType(
                   SyntaxFactory.Token(
                      SyntaxKind.StringKeyword)))) 
    

    which has the desired result

    Friend Property MyProperty As String