Skip to content

The SyntaxGenerator class does not generate default values for parameters of methods/constructors. #11734

@andriipatsula

Description

@andriipatsula

The SyntaxGenerator class does not generate default values for parameters of member/constructor/operator.

SyntaxGenerator.cs#L171:

internal SyntaxNode MethodDeclaration(IMethodSymbol method, string name, IEnumerable<SyntaxNode>? statements = null)
{
    var decl = MethodDeclaration(
        name,
        parameters: method.Parameters.Select(p => ParameterDeclaration(p)),
// ...

we call public SyntaxNode ParameterDeclaration(IParameterSymbol symbol, SyntaxNode? initializer = null) method providing the first parameter and never the second one.

IParameterSymbol has next properties:

  • bool HasExplicitDefaultValue { get; }
  • object? ExplicitDefaultValue { get; }

We can generate default values for parameters if HasExplicitDefaultValue is set. I believe the internal class Microsoft.CodeAnalysis.CSharp.CodeGeneration.ExpressionGenerator is responsible for generating default values.

internal static ExpressionSyntax GenerateExpression(
    ITypeSymbol? type,
    object? value,
    bool canUseFieldReference)
internal SyntaxNode MethodDeclaration(IMethodSymbol method, string name, IEnumerable<SyntaxNode>? statements = null)
{
    var decl = MethodDeclaration(
        name,
-        parameters: method.Parameters.Select(p => ParameterDeclaration(p)),
+        parameters: method.Parameters.Select(p => ParameterDeclaration(p, p.HasExplicitDefaultValue ? ExpressionGenerator.GenerateExpression(p.Type, p.ExplicitDefaultValue) : null)),
// ...

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions