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.
public OuterClass()
{
_InnerClass InnerClass = new _InnerClass();
}
You are creating a local variable InnerClass in your constructor - that won't help you - you need the property:
InnerClass = new _InnerClass();
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.
_InnerClass InnerClass = new _InnerClass();
declares a local variable inside the constructor; it will be discarded immediately after the constructor has completed. If you do
InnerClass = new _InnerClass();
instead, you will actually set the member variable in the new instance of the outer class.
By the way, I strongly suggest that you call the inner class InnerClass and the variable _innerClass, since this adheres to the C# naming conventions; your current naming is bound to confuse most people.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With