-1

So, I have the following parent class;

class Parent {
   public Parent() {
      Console.WriteLine ("Parent class")
   }
}

And the following child class;

class Child : Parent {
   public Child() {
      Console.WriteLine("Child class")
   }
}

I know that the constructor of the Child class automatically calls : base()(or however you call the constructor of the parent from inside the child class). Is there a way to get all of the static functions of the parent without initializing it? (maybe using interfaces?) What would be the way to call the parents constructor from inside the child class (maybe with certain arguments)?

Thanks.

2 Answers2

2

You should be able to write what I think is the simpler and cleaner way:

class Parent
{
  public Parent()
  {
    if ( GetType() != typeof(Parent) ) return;
    Console.WriteLine("Parent class");
  }
}

class Child : Parent
{
  public Child()
  {
    Console.WriteLine("Child class");
  }
}

static private void Test()
{
  var instance1 = new Parent();
  Console.WriteLine("-");
  var instance2 = new Child();
}

Output

Parent class
-
Child class

I do not recommend doing this kind of thing that is an anti-OOP pattern, and instead rethinking the design of the classes.

But if there is a good reason to do that, you're done.

How can I prevent a base constructor from being called by an inheritor in C#? (SO)

How can I prevent a base constructor from being called by an inheritor in C#? (iditect.com)

Ignoring Base Class Constructor (typemock.com)

0

Static methods are in class scope (not in instance scope). So they cannot be inheritated. Call of parent constructor in child the same as call of default constructor.

class Parent {
  public Parent(string param) {
  }
}

class Child : Parent {
  public Child() : base("parameter") {
  }
}

class Child2 : Parent {
  public Child(string param1, int param2) : base(param1) {
  }
}
BambinoUA
  • 6,126
  • 5
  • 35
  • 51