How to display/print type casted enum as string without using variable

Hi, refer the sample code below,

I want to print a bunch of typecasted enum values, both name and number values.
It seems I must store the type casted value in some enum variable to be able to print it’s name value through %s or to use the .name() method.

I want to print lots of such values each with their own enum types. Declaring variables for each of their enum types is not practical.

I couldn’t find any online examples printing enum names without variables, so, I wanted to ask here, if there is a way to directly print the typecasted enums at all? Or I must use a variable?

Thanks in advance!

 module temp();

   typedef enum bit [1:0] {A = 0, B, C, D} testEnum;
   logic [1:0] Var1 = '1;
  
   //1
   $display("%s(%h)", testEnum'(Var1), Var1); //prints <unknown character >(3)
 
   //2
   $display("%s(%h)", testEnum'(Var1).name(), Var1); //error at .name()
 
   //3
   testEnum Var1Enum = testEnum'(Var1);
   $display("%s(%h)", Var1Enum, Var1Enum); //prints D(3) - ### ideal result ###
 
 endmodule

Prior to the IEEE 1800-2023 SystemVerilog LRM, .name() method could only be used on a variable. The latest LRM adds function method chaining, which BTW, most tools have supported for years.

function testEnum toE(int in);
  return testEnum'(in);
endfunction
initial $display("%s(%h)", toE(Var1).name(), Var1);

To make this work for many different enum types, wrap this function as a static method of a parameterized class.

 class Eutil#(type E);
    static function E toE(int in);
      return E'(in);
    endfunction
  endclass
  initial $display("%s(%h)", Eutil#(testEnum)::toE(Var1).name(), Var1);

That’s perfect! Thank you so much Dave!