jeudi 7 janvier 2021

How to return the syntactic context of a C# method call

If you write something like

this.MyMethod(this.MyMethod(myParam)).Should().BeNull();

using the FluentAssertions library, an exception is thrown when the assertion fails, with the message

Expected this.MyMethod(this.MyMethod(myParam)) to be <null>, but found "foo".

How does it manage to get the syntactic context of the method call in order to produce such a meaningful exception message? Obviously some kind of reflection is used and probably some stack trace inspection (indeed, it only works properly in Debug mode and when the expression is written in a single line), but how exactly?

More specifically, is it possible to write a method with the signature

public static string GetSyntacticContext(object parameter);

satisfying (in Debug mode) the following?

GetSyntacticContext("foo")
    .Should().Be("\"foo\"");

GetSyntacticContext(myParam + 1)
    .Should().Be("myParam + 1");

GetSyntacticContext(this.MyMethod(this.MyMethod(myParam)))
    .Should().Be("this.MyMethod(this.MyMethod(myParam))");




Aucun commentaire:

Enregistrer un commentaire