Tutorials

Learn More

To refer to class properties or methods of the current class instance, this keyword is used. In simple terms, this keyword is a handle of the current class object. It shall be used only in non-static class methods.

The this keyword resolves the ambiguity of a compiler when class properties and arguments passed to class methods are the same.

Example without this keyword

class transaction;
  bit [31:0] data;
  int id;
  
  function new (bit [31:0] data, int id);
    data = data;
    id = id;
  endfunction
endclass

module class_example;
  initial begin
    transaction tr = new(5, 1);
    $display("Value of data = %0h, id = %0h", tr.data, tr.id);
  end
endmodule

Output:

Value of data = 0, id = 0

Example with this keyword

class transaction;
  bit [31:0] data;
  int id;
  
  function new (bit [31:0] data, int id);
    this.data = data;
    this.id = id;
  endfunction
endclass

module class_example;
  initial begin
    transaction tr = new(5, 1);
    $display("Value of data = %0h, id = %0h", tr.data, tr.id);
  end
endmodule

Output:

Value of data = 5, id = 1

Example for this keyword with static method

As mentioned before, this keyword usage in the static method is illegal. A compilation error is expected.

class transaction;
  bit [31:0] data;
  int id;
  
  static function assign_val (bit [31:0] data, int id);
    this.data = data;
    this.id = id;
  endfunction
endclass

module class_example;
  initial begin
    transaction tr = new();
    tr.assign_val(5,1);
    $display("Value of data = %0h, id = %0h", tr.data, tr.id);
  end
endmodule

Output:

Error-[SV-IUTS] Illegal use of this and super
testbench.sv, 8
  Use of 'this' and 'super' is not allowed inside 'static' class-method

Error-[SV-IUTS] Illegal use of this and super
testbench.sv, 9
  Use of 'this' and 'super' is not allowed inside 'static' class-method

Example for this keyword with non-static method call with static variable type

As discussed in the previous post in function static or task static method call, it is possible to use this keyword.

class transaction;
  bit [31:0] data;
  int id;
  
  function static assign_val (bit [31:0] data, int id);
    this.data = data;
    this.id = id;
  endfunction
endclass

module class_example;
  initial begin
    transaction tr = new();
    tr.assign_val(5,1);
    $display("Value of data = %0h, id = %0h", tr.data, tr.id);
  end
endmodule

Output:

Value of data = 5, id = 1

System Verilog Tutorials