I’m trying to have logical separators keeping all my properties logically separate, but so I only have to pass around a single object. What I’m saying is, I want to instantiate Object, and be able to use Object.InnerObject.InnerObjectsProperty. Here’s the code I’m testing to try to figure out how to do this:
namespace SubclassTesting
{
class Program
{
static void Main(string[] args)
{
int x;
Console.WriteLine("type a number");
x = Convert.ToInt32(Console.ReadLine());
OuterClass TestClass = new OuterClass();
TestClass.OuterNumber = x;
TestClass.InnerClass.InnerNumber = x;
Console.WriteLine("success!");
Console.ReadKey();
}
}
class OuterClass
{
public OuterClass()
{
_InnerClass InnerClass = new _InnerClass();
}
public int OuterNumber { get; set; }
public class _InnerClass
{
public int InnerNumber { get; set; }
}
public _InnerClass InnerClass { get; set; }
}
}
this code fails on TestClass.InnerClass.InnerNumber = x; with a NullReferenceException – Object reference not set to an instance of an object.
The constructor does nothing, it seems, and it fails to work both with and without.
Is this even possible? I want to instantiate the single OuterClass object, and have all the contained objects instantiate, and be accessible through the OuterClass object. This way I only have to pass a single object to and from methods, but can keep the inner workings logically separate from each other.
You are creating a local variable
InnerClassin your constructor – that won’t help you – you need the property:I question the whole approach though. In general I don’t see what nested classes buy you here and in general I would try to avoid them since they add complexity.