locked
Object reference not set to an instance of an object. for array?

    Question

  •  public void checkClass(string[] sq)
            {
                HashSet<int>[] valuesOfKey = new HashSet<int>[sq.Length];

    //code

    }

    Now I am accessing valueOfKey[0]= a["A"] (where a=new Dictionary<string, HashSet<int>>())

    Then it gives me above error?

    Whether I have to use new key word for ever index of valueOfKey??

    Saturday, June 28, 2014 2:16 PM

Answers

  • FYI,int[] i=new int[10] will get initialized to 0 because it is of Value type(Refer here) and in your case HashSet,which is of reference type and its value will be initialized to  null.
    Saturday, June 28, 2014 4:13 PM

All replies

  • This is because you have Initialized and Array of Hashset(valuesOfKey),and these values are not Initialize.They are Null.Except the First Element valueofKey[0]=a["A].So if you try to access other than the First Element you will get the error Object Reference not set to instance.Instead you can try to initialize the valuesofkey with some default value and then try to access the elements.

    May be something like this

    int mydefaultvalue=0;

    for(int i=0;i<sq.Length;i++)

    {

    valueofKey[i]=mydefaultvalue;

    }

    and then...

    valueOfKey[0]= a["A"]


    Saturday, June 28, 2014 3:29 PM
  • Thnx Rangesh,

    I did that already but if I am initializing the object of araay the internal object should be initialized.Means if we say int[] i= new int[10];

    in that case all array elements are get initialized. I am expecting same case here. I think another there may be some way for this.

    Saturday, June 28, 2014 3:56 PM
  • FYI,int[] i=new int[10] will get initialized to 0 because it is of Value type(Refer here) and in your case HashSet,which is of reference type and its value will be initialized to  null.
    Saturday, June 28, 2014 4:13 PM