this keyword in SystemVerilog

SystemVerilog this keyword


this keyword is used to refer to class properties. this keyword is used to unambiguously refer to class properties or methods of the current instance. this is a pre-defined class handle referring to the object from which it is used, calling this.variable means object.variable.
  • this keyword shall only be used within non-static class methods
  • this keyword refers to the object handle in which it is invoked

SystemVerilog this keyword
this keyword SystemVerilog

*Click on image for a better view

this keyword example


In the example below,

The addr, data, write and pkt_type are the property of both class and an argument to the function new, as the name in both are same.this will lead to an ambiguity in assignment and values will not be assigned properly.

class packet;
  
  //class properties
  bit [31:0] addr;
  bit [31:0] data;
  bit   write;
  string  pkt_type;
  
  //constructor
  function new(bit [31:0] addr,data,bit write,string pkt_type);
    addr  = addr;
    data  = data;
    write = write;
    pkt_type = pkt_type;
  endfunction
  
  //method to display class prperties
  function void display();
    $display("---------------------------------------------------------");
    $display("\t addr  = %0h",addr);
    $display("\t data  = %0h",data);
    $display("\t write = %0h",write);
    $display("\t pkt_type  = %0s",pkt_type);
    $display("---------------------------------------------------------");
  endfunction
  
endclass

module sv_constructor;
  packet pkt;

  initial begin
    pkt = new(32'h10,32'hFF,1,"GOOD_PKT");
    pkt.display();
  end
  
endmodule

 Simulator Output  

addr = 0
data = 0
write = 0
pkt_type =
Execute the above code on 



 Example -2 

The above problem can be overcome by using "this" keyword to the class properties.

class packet;
  
  //class properties
  bit [31:0] addr;
  bit [31:0] data;
  bit   write;
  string  pkt_type;
  
  //constructor
  function new(bit [31:0] addr,data,bit write,string pkt_type);
    this.addr  = addr;
    this.data  = data;
    this.write = write;
    this.pkt_type = pkt_type;
  endfunction
  
  //method to display class prperties
  function void display();
    $display("---------------------------------------------------------");
    $display("\t addr  = %0h",addr);
    $display("\t data  = %0h",data);
    $display("\t write = %0h",write);
    $display("\t pkt_type  = %0s",pkt_type);
    $display("---------------------------------------------------------");
  endfunction
  
endclass

module sv_constructor;
  packet pkt;

  initial begin
    pkt = new(32'h10,32'hFF,1,"GOOD_PKT");
    pkt.display();
  end
  
endmodule

 Simulator Output  

addr = 10
data = ff
write = 1
pkt_type = GOOD_PKT
Execute the above code on