0

I have a class such as:

public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public override string ToString() => $"{LastName}, {FirstName}";
}

and I would like to be able to extract the ToString-expression in runtime using reflection like so:

var exp = typeof(Person).GetMethod("ToString").GetMethodBodyAsString();

where exp would be something like this: "${LastName}, {FirstName}" or at least enough to make it possible to reconstruct the expression with some more effort..

Is it possible to extract this from the IL-code returned by reflection on the method-body?

Andreas Zita
  • 7,232
  • 6
  • 54
  • 115
  • The C# code is compiled to IL. You could get the IL from the com piled assembly but I don't know if that will solve the issue you're looking at. What are you trying to achieve? – Wouter de Kort Sep 30 '21 at 16:22
  • 2
    Please read https://xyproblem.info/ and respond. If you really need the capability of getting to that format string, the easiest way to do it is to declare a property containing that string, and then use that string in a `string.Format()` call for your `ToString()` method. – Robert Harvey Sep 30 '21 at 16:26

0 Answers0