简体   繁体   中英

Assign a value to a property of a class within a class

I have the following code

class TopClass
{
    public string ClsProp1 { get; set; }
    public string ClsProp2 { get; set; }

    public SubClass ClsProp3 { get; set; }
}

class SubClass
{
    public string SCProp1 { get; set; }
    public string SCProp2 { get; set; }
}


class Program
{
    static void Main(string[] args)
    {

        Test.TopClass TCN = new Test.TopClass();

        TCN.ClsProp1 = "TCProp1--string value";
        TCN.ClsProp2 = "TCProp2--string value";
        TCN.ClsProp3.SCProp1 = "SCProp1--string value";
        TCN.ClsProp3.SCProp2 = "SCProp2--string value";

    }
}

I can't seem to figure out how to instantiate the TCN.ClsProp3.ScProp1 and TCN.ClsProp3.ScProp2 values. I keep getting the "An unhandled exception of type 'System.NullReferenceException' occurred in Test.exe Additional information: Object reference not set to an instance of an object." error message. Forgive my ignorance, I'm really trying to learn OOP from scratch.

Thanks in advance

You need to initialize the ClsProp3 object before you can use it.

TCN.ClsProp3 = new SubClass();

You could also initialize it in the TopClass constructor like this:

class TopClass
{
    public TopClass()
    {
        ClsProp3 = new SubClass();
    }
    public string ClsProp1 { get; set; }
    public string ClsProp2 { get; set; }

    public SubClass ClsProp3 { get; set; }
}

When learning, it's better to pick a good domain. TopClass with ClsPropX do not make for a nice learning experience.

As for your original question, launch the debugger and see what the ClsProp3 equals to. And bear in mind that it's impossible to assign anything to "nothingness", which is null in C# parlance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM