Mackenzie Thomas

Mackenzie Thomas

  • 1.6k
  • 2
  • 228

How to instantiate derivative nested class

Dec 26 2023 1:52 AM

I am trying to get a object structure such that when someone calls base.two.three.four...seven seven is a getter that would get the value as well as logically inherit values the previous levels. I am trying to figure out how to accomplish this with C# as different variations that I've tried I get a stack overflow or unhandled exception. I remember this being easier with Java. The following is just basic code to acomplish a couple levels:

using System;
                    
public class Program
{
    public static void Main()
    {
        test test = new test();
        
        Console.WriteLine(test.a);
        Console.WriteLine(test.Ic.a);
        Console.WriteLine(test.Ic.b);
    }
}

public class test
{
    public test()
    {
    }
    
    public testinner Ic {get;set;}

    public int a = 1;
    
    public class testinner : test
    {
        public testinner()
        {
            a = 3;
        }
        
        public int a {get;set;}
        public int b = 2;
        
    }

    
}

When I run this I get:

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at Program.Main()
Command terminated by signal 6

Console.WriteLine(test.a); Correctly outputs 1, but the error occurs starting at the following lines:

Console.WriteLine(test.Ic.a);
Console.WriteLine(test.Ic.b);

The output is supposed to be: 1 3 2

How do I resolve this?


Answers (2)