0
using System;
namespace po {
  public class small {
    public string nem;
    public bool av = true;
    public void set_nem() {
      Console.WriteLine("enter name smaller");
      nem = Console.ReadLine();
    }
  }
  public class normal {
    public string nem;
    public small[] _small = new small[10];
    public void add_small() {
      for (int i = 0; i < 10; i++)
        _small[i] = new small();

      for (int i = 0; i < 10; i++) {
        if (_small[i].av == true){
          _small[i].set_nem();
          i = 11;
          }
      }

    }
    public void set_nem() {
      Console.WriteLine("enter name normal");
      nem = Console.ReadLine();
    }
  }

  public class big {
    public normal[] _normal = new normal[10];
    public void setup_big() {
      for (int i = 0; i < 10; i++)
        _normal[i] = new normal();
    }
  }

  class MainClass {
    public static void Main(string[] args) {
      var _big = new big();
      
      _big._normal[0]._small[0].set_nem();

    }
  }

}

the error that I am getting is this

Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object
  at po.MainClass.Main (System.String[] args) [0x00010] in <a57fc2b0e49a4f36b31cfb468d3661d3>:0 
[ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object
  at po.MainClass.Main (System.String[] args) [0x00010] in <a57fc2b0e49a4f36b31cfb468d3661d3>:0 

I know, its a pretty common error that beginners do but I really can't figure out where the problem is. I have tried making a constructor for small but nothing, I just complicate the problem. I tried searching for this error online and found this :

C# System.NullReferenceException: Object reference not set to an instance > of an object

The error is the same but I really can't fix it.

mike21
  • 7
  • 1
    The way to fix this is step through your code with a debugger and see what is null when you try to access it. – Jamiec Jan 06 '21 at 15:47
  • 2
    As a hint: `public normal[] _normal = new normal[10];` does not initialise the instances in that arry - it only reserve some (null) space for instances of `normal`. You have a method `setup_big` which does instantiate instances into your array which you never call! – Jamiec Jan 06 '21 at 15:48
  • btw, you may want to read about "properties" in C# (instead of "set_xy()" methods) https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties and constructors (instead of "setupxy()" methods) https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constructors – Christoph Lütjen Jan 06 '21 at 15:52

0 Answers0