JL.
JL.

Reputation: 81262

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
   {

   }
}

Upvotes: 3

Views: 4030

Answers (4)

Tim Goodman
Tim Goodman

Reputation: 23976

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.

Upvotes: 1

zerkms
zerkms

Reputation: 254916

It doesn't matter in what scope class has been declared - you should always work with classes in the same manner: before interacting with a particular class instance you have to create it using new operator.

Upvotes: 9

Mark Byers
Mark Byers

Reputation: 838186

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.

Upvotes: 2

Tom Cabanski
Tom Cabanski

Reputation: 8018

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.

Upvotes: -1

Related Questions