简体   繁体   中英

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???

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";
}

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

Members are not implicitly constructed. They're initialized with their default values (ie 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 (ie 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
  }
}

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