简体   繁体   中英

C# do nested classes need to be instantiated?

In the following scenario:

public class outerclass
{
   public innerClass Ic
     {get;set}

   public class innerClass
   {

   }
}

Do you need to instantiate the inner class property before assigning values to it, like this?

public class outerclass
{
   public outerclass()
     {
        this.Ic = new innerClass(); 
     }

   public innerClass Ic
     {get;set}

   public class innerClass
   {

   }
}

在声明的范围类中无关紧要 - 您应该始终以相同的方式使用类:在与特定类实例交互之前,您必须使用new运算符创建它。

Yes, unlike a base class you need to instantiate an inner class if you wish to use it.

You can prove this to yourself quite easily by trying it:

public class OuterClass
{
    public InnerClass Ic { get; set; }

    public class InnerClass
    {
        public InnerClass()
        {
            Foo = 42;
        }

        public int Foo { get; set; }
    }
}

public class Program
{
    static void Main()
    {
        Console.WriteLine(new OuterClass().Ic.Foo);
    }
}

The above code throws a NullReferenceException because Ic has not been assigned.

I would also advise you to follow the Microsoft naming convention and use pascal case for type names.

In this case the answer doesn't depend on the fact that the class is defined inside your outer class. Because you used the automatic getter/setter, a hidden backing field is used for the property Ic . Like all fields of reference type, this field has a default value of null . Thus if you try to access the members of Ic without setting it to refer to some instance, you can expect a NullReferenceException .

Everything I just said would still be true even if innerClass was defined somewhere else.

No, the property is an instance of the class. The set would set a new instance anyway. No need to construct one unless you want to make sure the get never returns null.

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