# Constrain the number of occurrences in an array

**URL:** <https://verificationacademy.com/forums/t/constrain-the-number-of-occurrences-in-an-array/33293>\
**Category:** SystemVerilog\
**Tags:** SystemVerilog, constraint, array-randomization\
**Created:** [July 12, 2017, 5:24pm UTC](https://verificationacademy.com/forums/t/constrain-the-number-of-occurrences-in-an-array/33293 "2017-07-12T17:24:13Z")\
**Posts on this page:** 1\
**Showing post:** 7

<div class="post-metadata">

**Author:** ![juhi\_p](https://verificationacademy.com/forums/letter_avatar_proxy/v4/letter/j/e0b2c6/32.png) [@juhi\_p](https://verificationacademy.com/forums/u/juhi_p)\
**Post date:** [November 8, 2020, 6:25am UTC](https://verificationacademy.com/forums/t/constrain-the-number-of-occurrences-in-an-array/33293/7 "2020-11-08T06:25:43Z")

</div>

_In reply to [dave\_59](https://verificationacademy.com/forums/t/constrain-the-number-of-occurrences-in-an-array/33293/6):_  
I tried with this:

```auto
class c;
  rand enum {ADD, SUB, MUL, DIV} e;
endclass

class txn;
rand c c_inst[];

  function void pre_randomize();
    for(int i=0;i<10;i++)begin
      c_inst[i]= new();
      c_inst[i].randomize();
    end
  endfunction

constraint add_less_than_5 {c_inst.sum() with (int'(item.e == c::ADD)) == 5;}

endclass

module abc;
  txn t1;
  
  initial begin
    t1=new();
    repeat(10) begin
      assert(t1.randomize());
      $display("%p",t1);
    end
  end
endmodule

```

but getting this

```auto
# ** Error: (vsim-7100) Invalid call to class::randomize() via a null class reference.
# Time: 0 ns Iteration: 0 Process: /abc/#INITIAL#24 File: testbench.sv Line: 13
# ** Error: (vsim-7100) Invalid call to class::randomize() via a null class reference.
# Time: 0 ns Iteration: 0 Process: /abc/#INITIAL#24 File: testbench.sv Line: 13
# ** Error: (vsim-7100) Invalid call to class::randomize() via a null class reference.
# Time: 0 ns Iteration: 0 Process: /abc/#INITIAL#24 File: testbench.sv Line: 13
# ** Error: (vsim-7100) Invalid call to class::randomize() via a null class reference.
# Time: 0 ns Iteration: 0 Process: /abc/#INITIAL#24 File: testbench.sv Line: 13
# ** Error: (vsim-7100) Invalid call to class::randomize() via a null class reference.
# Time: 0 ns Iteration: 0 Process: /abc/#INITIAL#24 File: testbench.sv Line: 13
# ** Error: (vsim-7100) Invalid call to class::randomize() via a null class reference.
# Time: 0 ns Iteration: 0 Process: /abc/#INITIAL#24 File: testbench.sv Line: 13
# ** Error: (vsim-7100) Invalid call to class::randomize() via a null class reference.

```

Can you please tell me reason for this?

---

_[View the full topic](https://verificationacademy.com/forums/t/constrain-the-number-of-occurrences-in-an-array/33293)._
