简体   繁体   中英

C# Class Property - Having Trouble Setting & Getting

I've set up a very simple C# class (code below) and have successfully run set/get on its properties. However I cannot access nested classes.

This is the code for the class (or rather, a simplification of it).

class TestClass
{
    public string example { get; set; }
    public NestedClass nestedclass { get; set; }

    public class NestedClass 
    {
        public string nestedExample { get; set; }
    }
}

And here is the function that gets/sets properties. I can set & get

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        //initialize new TestClass
        TestClass testclass = new TestClass();
        //assign arbitrary value to testclass.example
        testclass.example = "this works fine";

        //TestLabel content is changed to "this works fine", no issues
        TestLabel.Content = testclass.example;

        //now assign a value to nestedExample
        testclass.nestedclass.nestedExample = "this doesn't";

        //this will return System.NullReferenceException: 'Object reference not set to an instance of an object.' How come?
        TestLabel2.Content = testclass.nestedclass.NestedExample;

    }

I would expect the code above to set the value of testclass.nestedclass.nestedExample to "this doesn't", but for some reason it returns the error above. Anyone know where I've gone wrong?

You need to intialise it in some way

Example

class TestClass
{
    public string example { get; set; }
    public NestedClass nestedclass { get; set; } = new NestedClass();

or

class TestClass
{
    public string example { get; set; }
    public NestedClass nestedclass { get; set; }

    public TestClass ()
    {
        nestedclass = new NestedClass();
    }

or just initalize it before you use it.


However, while we are here.

  1. Not many people name properties with lower case
  2. Not many people would actually nest this class with in the other, there are very few uses cases for this, and just clutters your code.

You need to instantiate the nested class first before assigning any value.

testclass.nestedclass = new TestClass.NestedClass();

testclass.nestedclass.nestedExample = "this does now";

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