-2
using System;
namespace ss{
class NUM{
  public int[] numbers;
}
class MainClass {
  public static void Main (string[] args) {
    var num = new NUM();
    num.numbers[90] = 12;
    Console.WriteLine (num.numbers[90]);
  }
}
}

when I execute this code I get this error, it never happened to me

System.NullReferenceException: Object reference not set to an instance of an object
  at ss.MainClass.Main
mike21
  • 7
  • You never initialize the array, you only declare it `public int[] numbers;`. Until you give it a specified length, it will remain null. Before saying that `num.numbers[90] = 12;` you have to define the array's length. – Scopperloit Jan 07 '21 at 10:45

1 Answers1

2

So your problem is pretty simple!

You have initialized the class but not the array so it is referring to null!

There are two solutions to this.

First Add an initialization to the class[in constructor] it self!

using System;
namespace ss{
class NUM{
  public int[] numbers;
 
  public NUM(int length){
      numbers = new int[length];
  }
}
class MainClass {
  public static void Main (string[] args) {
    var num = new NUM(100);
    num.numbers[90] = 12;
    Console.WriteLine (num.numbers[90]);
  }
}
}

Second you could initialize the array in the MainClass:

using System;
namespace ss{
class NUM{
  public int[] numbers;
}
class MainClass {
  public static void Main (string[] args) {
    var num = new NUM();
    num.numbers = new int[100];
    num.numbers[90] = 12;
    Console.WriteLine (num.numbers[90]);
  }
}
}
Jaysmito Mukherjee
  • 1,467
  • 2
  • 10
  • 29