Pablo Pablo - 1 month ago 5
C# Question

How to extract a complete method inside a class?

I'm trying to extract a complete method which is inside a cs file.
for instance.. suppose we have a class like this...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GetMethodNm
{
class MyClass
{

public int ComplexMethod(int param1, int myCustomValue)
{
if (param1 == myCustomValue)
{
return 54;
}
else
{
return 0;
}
}

public string ComplexMethodV(int param1, int myCustomValue)
{
if (param1 < myCustomValue)
{
return "300";
}
else
{
return "My custom value to return";
}
}

public bool ComplexMethodX(int param1, int myCustomValue)
{
if (param1 == myCustomValue)
{
return true;
}
else
{
return false;
}
}
}
}


Then I need to extract the method reading the cs file ComplexMethodV .. How can I do this? I have tried with reflection but I can only get the name and some things inside of it.. but I would need the literal method within.

Answer

Using Roslyn tasks like this are relitively easy. In a project add the NuGet package Microsoft.CodeAnalysis.CSharp, then just use the following code

using System;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace SandboxConsole
{
    class Program
    {
        public static void Main()
        {
            var text = File.ReadAllText("MyClass.cs");
            var tree = CSharpSyntaxTree.ParseText(text);

            var method = tree.GetRoot().DescendantNodes()
                         .OfType<MethodDeclarationSyntax>()
                         .First(x => x.Identifier.Text == "ComplexMethodV");

            Console.WriteLine(method.ToFullString());
            Console.ReadLine();
        }
    }
}

This outputs the text

        public string ComplexMethodV(int param1, int myCustomValue)
        {
            if (param1 < myCustomValue)
            {
                return "300";
            }
            else
            {
                return "My custom value to return";
            }
        }

See the Wiki for more advanced tutorials on how to do things like parse entire solutions.