Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add parameters to generated method in Roslyn ( Microsoft.CodeAnalysis )? - Need exact syntax

Below is the function I'm using to generate a simple method -

//NOTE : SF = SyntaxFactory
        List<ParameterSyntax> parameterList = new List<ParameterSyntax>
        {
            SF.Parameter(SF.Identifier(sourceObjectName))
        };
        // Create method
        var method = SF.MethodDeclaration(SF.ParseName(destinationClass), functionName)
            .WithBody(SF.Block(nodes))  
            .AddModifiers(SF.Token(SyntaxKind.PublicKeyword))
            .AddParameterListParameters(parameterList.ToArray())
            .NormalizeWhitespace();
        // NEED TO ADD PARAMS TO CODE
        Console.WriteLine(method.GetText());

And here's the output:

public XYZ MapABCToXYZ(fromObject) // Should be 'ABC fromObject'
{
    XYZ myObject = new XYZ();
    myObject.MyProperty = fromObject.MyProperty;
    myObject.TestProperty = fromObject.TestProperty;
    return myObject;
}

As you can see, the parameter is not "ABC fromObject" and I've been trying to figure out the exact syntax to add parameters properly.

I've tried various ways to figure out the parameter syntax and have come up blank mostly.

EDIT: Figured it out. Just had to make a change in the following line:

SF.Parameter(SF.Identifier(sourceObjectName)).WithType(SF.ParseTypeName(sourceClass))
like image 446
Nitish Victor Avatar asked Apr 22 '15 04:04

Nitish Victor


1 Answers

As suggested, I'm posting the solution here -

Figured it out. Just had to make a change in the following line:

SF.Parameter(SF.Identifier(sourceObjectName)).WithType(SF.ParseTypeName(sourceClass))

Where 'sourceClass' is a string of the required type.

like image 150
Nitish Victor Avatar answered Sep 20 '22 13:09

Nitish Victor