C # do i need to create nested classes?

In the following scenario:

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

   public class innerClass
   {

   }
}

Do you need to instantiate an internal property of a class before assigning values ​​to it?

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

   public innerClass Ic
     {get;set}

   public class innerClass
   {

   }
}
+3
source share
4 answers

It doesn’t matter in which class the class was declared - you should always work with the classes in the same way: before interacting with a specific instance of the class, you must create using the newoperator.

+9
source

Yes, unlike the base class, you need to instantiate the inner class if you want to use it.

You can easily prove it to yourself by trying:

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 it is Icnot assigned.

Microsoft .

+2

, . /, Ic . , null. , Ic, - , NullReferenceException.

, , , innerClass - .

+1

, . . , , get null.

-1

Source: https://habr.com/ru/post/1745888/


All Articles