0

We use our "own" assert methods which allow to pass a message but do not force it. Most of our code base use the "without message" one... Which is problematic when you have more than one assert and the code changes between the bug reporting and the bug fixing...

I would like to print, in the assert message, the caller line in plain text. Something like:

int toto = 1;
SomObject obj = null;

Assert(toto == 0);
Assert(obj);
Assert(toto == 0, "some useful info");

Expected output:

Assertion failed. Parameter='toto == 0'
Assertion failed. Parameter='obj'
Assertion failed. 'some useful info'

We found this thread talking about Cecil Mono.Cecil - simple example how to get method body ...

It could be a way to go, but would means we have to rebuild the line based on the ILCode. Is there a way to get the "plain text code" in an other way?

[EDIT] We are running on C# 8.

Thor Tillas
  • 115
  • 7

1 Answers1

7

You can try CallerArgumentExpressionAttribute (https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callerargumentexpressionattribute?view=net-6.0) to get actual assert expression/condition and show it as a message.

public static void Assert(bool condition, 
    [CallerArgumentExpression("condition")] string message = null)
{
    //code here
}

Usage

// message argument in Assert will be "result==true" (as string)
Assert(result==true);

// message argument in Assert will be "Custom message"
Assert(result==true, "Custom message");
Serg
  • 3,454
  • 2
  • 13
  • 17
  • 2
    As the link says, this attribute is available starting from C#10 – Hans Kesting Jan 06 '22 at 07:34
  • arf... I was smiling until I read our comment ^^ As we are running on "Unity's C#" it's out of our reach for now... Nice to know there is a "simple" way to do it somewhere down the line. Thanks for the answer and the comment! – Thor Tillas Jan 07 '22 at 08:25
  • 1
    @ThorTillas, I unfamiliar with Unity limitations, but for ordinary C# CallerArgumentExpressionAttribute can be backported to older versions - see here for details https://stackoverflow.com/questions/70034586/how-can-i-use-callerargumentexpression-with-visual-studio-2022-and-net-standard/70034587#70034587 – Serg Jan 07 '22 at 09:17