Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

Class Handle: Associative Array

SystemVerilog Classes & OOP

Runnable example from the SystemVerilog Class Handle tutorial (Associative Array)

Open in IDE
design.sv
class Packet;
    int count;
    function new (int c = 0);
        count = c;
    endfunction
endclass
testbench.sv
module tb;

    // Declare an associative array where the key is a string and the value is a Packet object
    Packet assoc_array[string];

    initial begin
        $display("--- Associative Array Example ---");

        // Assign Packet objects to the associative array using string keys
        assoc_array["packet_A"] = new(50);
        assoc_array["packet_B"] = new(75);
        assoc_array["packet_C"] = new(100);

        // Access and display data using keys
        $display("assoc_array[\"packet_A\"].count = %0d", assoc_array["packet_A"].count);
        $display("assoc_array[\"packet_C\"].count = %0d", assoc_array["packet_C"].count);

        // Iterate through the associative array (order is not guaranteed unless specified)
      foreach (assoc_array[k]) begin
            $display("Key: %s, Count: %0d", k, assoc_array[k].count);
        end

        // Check if a key exists
        if (assoc_array.exists("packet_B")) begin
            $display("Packet_B exists in the associative array.");
        end
    end

endmodule  
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.