Aperture
Aperture

Reputation: 2427

In .NET, does a parent class' constructor call its child class' constructor first thing?

public class Parent
{
    Child child1;

    public Parent()
    {
        child1.Name = "abc";
    }
    ...
}

Gets a NullReferenceException. I thought the Parent() constructor calls the Child() constructor first, so that it is possible to access child1 object later in the Parent() constructor???

Upvotes: 0

Views: 225

Answers (3)

Håvard S
Håvard S

Reputation: 23886

Members are not implicitly constructed. They're initialized with their default values (i.e. null for reference type members), which is why your child1 member is null.

You need to create an instance of child1:

public Parent
{
  child1 = new Child();
}

On a sidenote, I think you are being confused by constructor call rules for inherited classes. If your Child class inherited your Parent class, the Parent class' default (i.e. parameterless) constructor would be implicitly called (if it existed):

class Parent
{
  protected string member;
  public Parent()
  {
    member = "foo";
  }
}

class Child : Parent
{
  public Child()
  {
    // member is foo here; Parent() is implicitly called
  }
}

Upvotes: 1

Andrew Barber
Andrew Barber

Reputation: 40160

You need to create an instance of the child; either initialize it as you define it:

Child child1 = new Child();

Or in the Parent constructor:

public Parent(){
    child1 = new Child();
    child1.Name = "Andrew";
}

Upvotes: 4

Ken Bloom
Ken Bloom

Reputation: 58800

The parent class's constructor doesn't call constructors for its members. When the member is a reference, it's just set to null. You need to explicitly allocate it by calling child1 = new Child

Upvotes: 2

Related Questions